在类中向量成员的奇怪现象 [英] A strange phenomenon of vector member in a class

查看:98
本文介绍了在类中向量成员的奇怪现象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有的头文件包括

class Test{ 
public:
    vector<int> vector_int(10);
    Test(int num);
    ~Test();
};

Test::Test(int num){
    cout << "constructor employed" <<endl;
    vector<int> vector_int;
    for (int i = 0; i < num; i++){
        vector_int.push_back(i);
    }
    cout<<"The size is " << vector_int.size()<<endl;
}

int main(){
    int num = 10;
    Test* a = new Test(10);
    cout<< a->vector_int.size()<< " is the size"<<endl;
    return 0;
}

结果:构造函数采用
大小为10

Result: constructor employed The size is 10

0是大小

在我看来,这些大小应该是相同的。还使用构造函数。

It seems to me that these sizes should be the same. The constructor is also employed. What is the problem then?

推荐答案

您正在隐藏类成员变量 vector_int

You are shadowing the class member variable vector_int with a local variable of the same name in the constructor.

删除向量< int>中的同一个局部变量。 vector_int; 从构造函数,它应该按预期工作。

Remove the line vector<int> vector_int; from the constructor and it should work as expected.

这篇关于在类中向量成员的奇怪现象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆