简体   繁体   中英

vector.size() returns 0 all the time

I have the following class:

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

The constructor and size function look like this:

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

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

However when running these lines:

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

The output is 0. Can anyone explain why is this happening?

Your constructor makes a local variable that shadows your member variable

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

Instead use the member initialization list

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM