簡體   English   中英

運算符重載代碼編譯錯誤,模板參數推導/替換失敗

[英]Operator overloading code compilation error, template argument deduction/substitution failure

我正在嘗試應用以下C ++類中學習的一些運算符加載概念。

#include<iostream>
using namespace std;

class Point
{
private:
    int x, y;
public:
    Point(int, int);
    Point operator+(const Point&);
    friend istream& operator>>(istream& in, Point&);
    friend ostream& operator<<(ostream& out, Point&);
    Point operator=(const Point&);
};

Point::Point(int x = 0, int y = 0)
    :x(x), y(y){}

Point Point::operator+(const Point& p)
{
    int r1, r2;
    r1 = x + p.x;
    r2 = y + p.y;
    return Point(r1, r2);
}

Point Point::operator=(const Point& p)
{
    this->x = p.x;
    this->y = p.y;
    return *this;
}

istream& operator>>(istream& in, Point& p)
{
    char openParenthesis, closeParenthesis, comma;
    cout << "Enter data in the format (1,2): ";
    in >> openParenthesis >> p.x >> comma >> p.y >> closeParenthesis;
    return in;
}

ostream& operator<<(ostream& out, Point& p)
{
    out << "(" << p.x << "," << p.y << ")";
    return out;
}

int main()
{
    Point a, b;
    cin >> a >> b;

    cout << "a + b is: " << a + b << endl;
    return 0;
}

該代碼可以在Visual Studio上編譯並正常運行。 但是,當我嘗試在Linux上使用gcc對其進行編譯時,它會拋出一系列錯誤:

在/usr/include/c++/4.8/iostream:39:0中包含的文件中,從optr_overload.cpp:1:/usr/include/c++/4.8/ostream:471:5:注意:模板std :: basic_ostream <_CharT ,_Traits>&std :: operator <<(std :: basic_ostream <_CharT,_Traits>&,_CharT)運算符<<(basic_ostream <_CharT,_Traits>&__out,_CharT __c)^ /usr/include/c++/4.8/ ostream:471:5:注意:模板參數推導/替換失敗:optr_overload.cpp:53:30:注意:
推導參數'_CharT'('char'和'Point')的沖突類型cout <<“ a + b是:” << a + b << endl;

我知道問題出在我將“ a + b”傳遞給重載的二進制流插入運算符的那行,該運算符僅接收對一個Point對象的引用作為參數。 但是除了將“ a + b”分配給第三個對象並將該單個對象作為參數傳遞給“ <<”之外,我不知道如何修復代碼。 有人可以向我解釋為了使gcc編譯我的代碼需要做什么,最好不涉及使用額外的占位符對象。

a + b計算的值是一個臨時對象,因此不能作為Point&傳遞給operator<< ; 該語言僅允許將臨時變量作為const Point&傳遞。 只需更改輸出運算符的聲明即可接受const Point&

在舊版本的VC ++中,允許將臨時結果作為非常量引用傳遞是已知的錯誤。

您幾乎一切都正確,但是您的ostream& operator<<()應該通過const引用獲取Point:

friend ostream& operator<<(ostream& out, const Point&);

這應該可以解決您的問題。

(並且不必擔心Point::xPoint::y是私有的,您已經聲明了operator<<為朋友。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM