如何使用向量和整数作为类的构造函数
如果我有一个 foo 类,那么
class foo{
vector <int> vec;
int someint;
public:
foo(number n): someint(n){}
}
我将如何为 class foo
的 vector
编写构造函数?此外,我可以使用:
int get_someint() const{
return someint;
}
返回一个 int
,但是向量呢?
If I had a class foo then
class foo{
vector <int> vec;
int someint;
public:
foo(number n): someint(n){}
}
How would I write a constructor for the vector
, for class foo
? Moreoever, I can use:
int get_someint() const{
return someint;
}
To return an int
, but what about vectors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当使用复杂的数据类型时,通常最好使用引用或常量引用,如下所示:
示例用法:
When working with complex data types, its usually best to work with references, or const-references like so:
Example usage:
你也可以这样做。出于所有目的,请将
vector
视为普通变量(例如int
),因此您可以编写:它将被内部和外部复制,并且这可能意味着大量的内存副本。这就是为什么对于如此大的对象,使用按引用传递(通过指针或引用)。例如,要返回向量:
,构造函数也将是 foo(number n, vectorconst& v)。另外,如果在内部您不必存储向量的副本,则可以使用该向量的指针或引用作为成员,而不是向量副本本身,即类是:(
注意引用) 。与指针相同。
You can do it just the same. For all purposes, consider
vector<int>
as a normal variable (like anint
, for example), so you can write:It will be copied inside and out, and that may mean a lot of memory copies. This is why for such large objects, pass by reference (either by pointer or reference) is used. For example, to return the vector:
and the constructor would be also
foo(number n, vector<int> const& v)
. Also, if internally you don't have to store a copy of the vector, you can use a pointer or reference to that vector as a member, instead of the vector copy itself, that is, the class being:(note the references). The same with pointers.
您不需要为向量编写构造函数。 Vector 已经有了它的构造函数。您也可以在返回 int 时简单地返回一个向量,例如
You don't need to write a constructor for the vector. Vector already has it's constructors. Also you can simply return a vector as you return your int e.g.