簡體   English   中英

運算符重載:簡單加法...錯誤C2677:二進制'+':找不到類型為___的全局運算符(或者沒有可接受的轉換)

[英]Operator Overloading: Simple Addition… error C2677: binary '+': no global operator found with takes type ___ (or there is not acceptable conversion)

這是我的標題:

//RINT.h
#ifndef _RINT_H_
#define _RINT_H_

#include <iostream>

class RINT
{
    public:
        RINT();
        RINT(int);
        RINT(int, int);
        RINT operator+(RINT);
        RINT operator+(int);
        RINT operator+();
        friend std::ostream &operator<<(std::ostream &, const RINT &);
        friend std::istream &operator>>(std::istream &, RINT &);
    private:
        int a, b;
};

#endif

以及定義:

//RINT.cpp
#include <iostream>
using namespace std;

#include "RINT_stack.h"

RINT::RINT()
{
    a = b = 0;
}

RINT::RINT(int x)
{
    a = x;
    b = 0;
}

RINT::RINT(int x, int y)
{
    a = x;
    b = y;
}

RINT RINT::operator+(RINT x)
{
    a += x.a;
    b += x.b;
    return RINT(a,b);
}

RINT RINT::operator+(int x)
{
    a += x;
    return RINT(a,b);
}

RINT RINT::operator+()
{
    return RINT(a,b);
}

ostream &operator<<(ostream &o, const RINT &x)
{
    o << x.a;
    o << x.b;
    return o;
}

istream &operator>>(istream &i, RINT &x)
{
    i >> x.a;
    i >> x.b;
    return i;
}

最后,測試代碼:

//RINT_test.cpp
#include "stdafx.h"
#include "RINT_stack.h"

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{
    RINT x, y = 4;
    int a = 5, b = 2;
    RINT z = y;

    x = 5;
    y = 6;
    z = x + y;
    z = x + 10;
    z = 1 + x; //error here!
    x = 1;
    x = +x;

    return 0;
}

我在“ z = 1 + x”的第20行的RINT_test.cpp中收到以下錯誤:

錯誤C2677:二進制'+':未找到采用'RINT'類型的全局運算符(或沒有可接受的對話)

我知道錯誤即將到來,因為運算符前面有一個整數,但是我不確定如何從此處繼續。 任何幫助或指導表示贊賞。 謝謝!

RINT RINT::operator+(RINT x)
{
    a += x.a;
    b += x.b;
    return RINT(a,b);
}

這不是const,會修改您在其上調用的對象,因此無法在臨時對象上調用。 因此,如果您期望z = 1 + x1創建一個臨時RINT ,然后在其上調用operator+ ,則不能。

你要:

RINT RINT::operator+(RINT const& x) const
{
    return RINT(a + x.a, b + x.b);
}

您在其他運算符中也有類似的錯誤。 像運營商+ 應該修改調用它們的對象。 c = a + b;代碼c = a + b; 不應更改ab的值。 只有像+=這樣的運算符才可以這樣做。

我知道錯誤即將到來,因為運算符前面有一個整數,但是我不確定如何從此處繼續。

是的,編譯器是正確的! 缺少 全球

RDINT operator+(const int&, const RDINT&);

要么

int operator+(const int&, const RDINT&);

聲明/定義!

您可能會注意到,上面的函數簽名示例的第一個參數與您提到的代碼示例中的前面的整數匹配。

暫無
暫無

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

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