【发布时间】:2017-04-03 10:55:40
【问题描述】:
我会尽量简化
在 Java 中,我会执行以下操作:
public class foo{
private final int x;
private final ArrayList<classname1> one;
private final ArrayList<classname2> two;
//constructor
public foo(int x){
this.x = x;
one = new ArrayList<>();
two = new ArrayList<>();
menu();
}
然后我会在我的代码中使用“一”和“二”
然而,我目前正在使用 c++,并且我读到 C++ 中 ArrayList 的等价物是向量。我已经尝试过尝试,但是我发现很难理解如何像 java 代码一样初始化构造函数中的向量。
这是我目前在 c++ 中所拥有的:
class foo{
private: int x;
private: vector<classname1> one;
private: vector<classname2> two;
public:
//constructor
foo(int x) {
this->x= x;
//how would I initialize the vectors here like in java? Something like but of course it doesn't work:
one = new Vector<>();
two = new Vector<>();
menu();
}
谢谢!任何帮助表示赞赏。
【问题讨论】:
-
这取决于您要将其初始化为什么,您应该澄清这一点。但是,如果您想要默认的初始化向量,什么都不做也没关系。
-
只是
foo(int val) : x(val) { menu(); }。one和two与foo对象在同一分配空间中。如果你想让它们独立于foo类,你应该用unique_ptr<vector<classname1>> one或另一个智能指针声明它。
标签: java c++ class arraylist vector