为什么下面的向量大小是0?
#include <iostream>
#include<vector>
using namespace std;
class A
{
public:
vector<int> T;
const vector<int>& get(){
return T;
}
void print(){
cout<< " size is "<<T.size();
// cout<<" nelements are %d "<<T[0];
}
};
int main()
{
cout << "Hello World" << endl;
A ob;
vector<int> temp = ob.get();
temp.clear();
temp.push_back(3);
temp.push_back(5);
ob.print();
return 0;
}
这是因为它什么也没发生。它仍然是空的。
您在 temp
中创建了向量的副本,并且修改了副本,而不是原始类成员。您应该使用引用:
vector<int> &temp = ob.get();
由于您要从 get()
返回引用,因此必须将其分配给引用。如果你不这样做,你只是在复制对象。
编辑:另外,更改get()
以返回可变引用,而不是const
引用。
您没有修改A
类内部的vector
。 get()
返回一个 (const!) 引用,然后您将其分配给非引用变量,因此正在创建vector
的副本。 然后,您正在修改副本,但打印出原始副本。
您需要改为执行以下操作:
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
vector<int> T;
vector<int>& get(){
return T;
}
void print(){
cout << " size is " << T.size();
// cout << " nelements are %d " << T[0];
}
};
int main()
{
cout << "Hello World" << endl;
A ob;
vector<int> &temp = ob.get();
temp.clear();
temp.push_back(3);
temp.push_back(5);
ob.print();
return 0;
}
两个问题。
首先,A::get()
方法返回对其成员的 const 引用。不能通过常量引用修改向量。
其次,您正在修改 temp
向量,该向量只是返回值的副本。