[英]How to override the ++ operator in C++ and then print the output using an overriden << operator?
I'm trying to learn overriding operators in C++. 我正在尝试学习C ++中的重载运算符。 But I'm stuck with this:
但我坚持这一点:
..\\src\\application.cpp: In function `int main()':
.. \\ src \\ application.cpp:在函数'int main()'中:
..\\src\\application.cpp:29: error: no match for 'operator<<' in 'std::operator<< [with _Traits = std::char_traits](((std::basic_ostream >&)(&std::cout)), ((const char*)"Poly A: ")) << (&A)->Poly::operator++(0)'
.. \\ src \\ application.cpp:29:错误:'std :: operator <<中的'operator <<'不匹配[带有_Traits = std :: char_traits]((((std :: basic_ostream>&)(&std :: cout)),((const char *)“ Poly A:”))<<(&A)-> Poly :: operator ++(0)'
Here's the line causing the error, It seems that my postincrement operator isn't returning anything printable: 这是导致错误的行,似乎我的postincrement运算符未返回任何可打印的内容:
cout << "Poly A: " << A++ << endl;
I have a Poly.h and a Poly.cpp file: 我有一个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.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;
}
I think the problem is that you declare your parameters as references: 我认为问题在于您将参数声明为引用:
ostream& operator<<(ostream &out, Poly &robject)
The reference will not bind to the temporaries that you return from your operator++
. 该引用将不会绑定到您从
operator++
返回的临时对象。 If you make the Poly
parameter a const
reference you should be able to output it. 如果将
Poly
参数设为const
引用,则应该可以将其输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.