【问题标题】:No viable overload for '=' when there is an operator当有运算符时,'=' 没有可行的重载
【发布时间】:2017-05-03 23:18:33
【问题描述】:
struct myType{
public:    

    myType operator=(const myType &value){
        return value;
    };

};

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;
};

我应该在重载=中更改什么来解决这个问题

【问题讨论】:

  • 通常赋值运算符的返回类型是对该类型的引用,在本例中为myType&amp;。您从 operator= 返回 myType 而不是 myType&amp;。不知道对你有没有帮助...
  • 我已经做了 const myType &value,和 const myType& value 一样,如果是你的意思
  • 不,const 对于参数是正确的,但对于返回类型不正确。
  • myType&amp; operator=(const myType &amp;value) { /*copy the data from value into this */; return *this; }。注意返回类型和返回值是什么(不是原来的,而是*this
  • js.allinfo.begin()是vector的成员,与myType无关

标签: c++ vector iterator operator-overloading


【解决方案1】:

您正在尝试使用非 const 迭代器迭代 const 对象(const JSON &js)。

使用 const 迭代器:

vector<myType>::const_iterator it;

更好的是,使用关键字“auto”来自动获取正确的类型:

auto it = js.allInfo.begin()

【讨论】:

  • 更好的是,使用 range-for 循环。
猜你喜欢
  • 2015-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
相关资源
最近更新 更多