繁体   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