Joh*_*eli 1 c++ iterator vector operator-overloading
struct myType{
public:
myType operator=(const myType &value){
return value;
};
};
Run Code Online (Sandbox Code Playgroud)
myType有一个运算符重载=但是当它在it = js.allInfo.begin();编译器的JSON类中被调用时抛出:"'='没有可行的重载"
class JSON{
private:
vector<myType> allInfo;
public:
friend ostream &operator<<(ostream &os,const JSON &js)
{
vector<myType>::iterator it;
for(it = js.allInfo.begin(); it != js.allInfo.end();it++){
cout << "this is the info "<<(it->getNAME()) << endl;
}
return os;
};
Run Code Online (Sandbox Code Playgroud)
我应该在重载中改变什么=来解决这个问题
您正在尝试使用非const迭代器迭代const对象(const JSON和js).
使用const迭代器:
vector<myType>::const_iterator it;
Run Code Online (Sandbox Code Playgroud)
更好的是,使用关键字"auto"自动获取正确的类型:
auto it = js.allInfo.begin()
Run Code Online (Sandbox Code Playgroud)