Bul*_*ali 2 c++ class vector c++11
我有以下课程:
class MyVector{
public:
MyVector(int num);
virtual ~MyVector();
int my_size();
private:
vector<int> some_vector;
};
Run Code Online (Sandbox Code Playgroud)
构造函数和大小函数如下所示:
MyVector::MyVector(int num) {
vector <int> some_vector(num);
}
int MyVector::my_size() {
return this->some_vector.size();
Run Code Online (Sandbox Code Playgroud)
但是,在运行这些行时:
MyVector *Bul = new MyVector(5);
cout << Bul->my_size() << endl;
Run Code Online (Sandbox Code Playgroud)
输出为 0。谁能解释为什么会这样?
您的构造函数创建了一个局部变量,该变量会影响您的成员变量
MyVector::MyVector(int num) {
vector<int> some_vector(num);
}
Run Code Online (Sandbox Code Playgroud)
而是使用成员初始化列表
MyVector::MyVector(int num)
: some_vector(num)
{
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |