如何覆盖 ++ C++ 中的运算符然后使用覆盖 << 打印输出操作员?

发布于 2024-08-14 17:44:20 字数 1206 浏览 5 评论 0 原文

我正在尝试学习 C++ 中的重写运算符。但我坚持这个:

..\src\application.cpp: 在函数 `int main()' 中:

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

这是导致错误的行,看来我的后增量运算符没有返回任何可打印的内容:

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

I'm trying to learn overriding operators in C++. But I'm stuck with this:

..\src\application.cpp: In function `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)'

Here's the line causing the error, It seems that my postincrement operator isn't returning anything printable:

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

I have a Poly.h and a Poly.cpp file:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

佞臣 2024-08-21 17:44:20

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

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

该引用不会绑定到您从 operator++ 返回的临时变量。
如果将 Poly 参数设置为 const 引用,您应该能够输出它。

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++.
If you make the Poly parameter a const reference you should be able to output it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文