Home Articles

如何在C中覆盖运算符,然后使用覆盖<<运算符打印输出?

Asked
Viewed 652 times
0

我正在尝试学习C中的覆盖运算符 . 但我坚持这个:

.. \ src \ application.cpp:在函数`int main()':.. \ src \ application.cpp:29:错误:'std :: operator <<中的'operator <<'不匹配[与_Traits = std :: char_traits](((std :: basic_ostream>&)(&std :: cout)),((const char *)“Poly A:”))<<(&A) - > Poly :: operator( 0)”

这是导致错误的行,似乎我的postincrement运算符没有返回任何可打印的内容:

cout << "Poly A: " << A++ << endl;

我有一个Poly.h和一个Poly.cpp文件:

class Poly{
friend istream& operator>>(istream &in, Poly &robject);
friend ostream& operator<<(ostream &out, Poly &robject);
public:
    Poly();

    Poly operator++(int);
    Poly operator++();      
private:
    int data[2];
};

Poly.cpp:

Poly Poly::operator++ (){
data[0]+=1;
data[1]+=1;
return *this;}

Poly  Poly::operator++ (int){
    Poly  result(data[0], data[1]);
        ++(*this);  
    return result;
}
ostream& operator<<(ostream &out, Poly &robject){ 
out << "(" << robject.data[0] << ", " << robject.data[1] << ")";
return out;
}

1 Answer

  • 4

    我认为问题在于您将参数声明为引用:

    ostream& operator<<(ostream &out, Poly &robject)
    

    引用不会绑定到从 operator++ 返回的临时值 . 如果将 Poly 参数设为 const 参考,则应该能够输出它 .

Related