C++ 修改引用返回的向量
为什么下方向量的大小为0C++ 修改引用返回的向量,c++,C++,为什么下方向量的大小为0 #include <iostream> #include<vector> using namespace std; class A { public: vector<int> T; const vector<int>& get(){ return T; } void print(){ cout&
#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;
}
#包括
#包括
使用名称空间std;
甲级
{
公众:
向量T;
常量向量&get(){
返回T;
}
作废打印(){
因为它什么也没发生。它还是空的
您在temp
中复制了向量,并修改了副本,而不是原始类成员。您应该使用引用:
vector<int> &temp = ob.get();
向量&temp=ob.get();
由于要从get()
返回引用,因此必须将其分配给引用。如果不这样做,则只需制作对象的副本
编辑:另外,更改
get()
以返回可变引用,而不是const
引用。您没有修改a
类内部的向量。get()
返回(const!)引用,然后将其分配给非引用变量,因此将创建向量的副本。然后修改副本,但打印出原始副本
您需要这样做:
#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;
}
#包括
#包括
使用名称空间std;
甲级
{
公众:
向量T;
向量&get(){
返回T;
}
作废打印(){
可能有两个问题
首先,您的A::get()
方法返回对其成员的常量引用。您不能通过常量引用修改向量
其次,您正在修改仅为返回值副本的temp
向量。请注意,get()
正在返回一个常量引用,不能将其分配给非常量引用。get()
的签名需要在返回值上删除const
(这是该问题的正确解决方案)正确编译。您是指vector&get()const
而不是const vector&get()
?