【问题标题】:vector.size() returns 0 all the timevector.size() 一直返回 0
【发布时间】:2020-07-28 20:07:00
【问题描述】:

我有以下课程:

class MyVector{
public:
    MyVector(int num);
    virtual ~MyVector();
    int my_size();
private:
    vector<int> some_vector;
};

构造函数和大小函数如下所示:

MyVector::MyVector(int num) {
    vector <int> some_vector(num); 
}

int MyVector::my_size() {
    return this->some_vector.size(); 

但是在运行这些行时:

MyVector *Bul = new MyVector(5);
    cout << Bul->my_size() << endl;

输出为 0。谁能解释为什么会这样?

【问题讨论】:

  • 欢迎来到 Stackoverflow。我建议你对 C++ 中的初始化列表做一些研究。
  • 无关:您不必使用指针和new 来代替BulMyVector Bul(5); 应该足够且易于管理。
  • 提高编译器的警告级别。它应该可以告诉你隐藏成员变量名的局部变量名。

标签: c++ class c++11 vector


【解决方案1】:

你的构造函数创建了一个局部变量来隐藏你的成员变量

MyVector::MyVector(int num) {
    vector<int> some_vector(num); 
}

改为使用成员初始化列表

MyVector::MyVector(int num)
  : some_vector(num)
{
}

【讨论】:

    猜你喜欢
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 2018-02-11
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多