繁体   English   中英

运算符未解析为运算符功能C ++

[英]operator not resolving to operator function c++

我一直在处理需要重载某些运算符的类(=,==,+,!=等),我编写了运算符函数,但有时未调用它们,或者编译器的行为类似于它甚至不存在。 例如:

class Thing{
public:
    Thing& operator=(const Thing& _other){
        // implementation 
    }
    bool operator==(const Thing& _other){
        // implementation
    }
    Thing& operator+(const Thing& _other){
        // implementation 
    }
};

这包括该类的其他成员函数(构造函数(默认),构造函数(复制),析构函数等),但有时该方法被忽略。

void Foo(Thing & thing1, Thing & thing2){
    //snip
    if(thing1 == thing2){
        //do some stuff
    }
    //snip
    Thing tempThing();
    thing1 = thing2 + &tempThing;
    //snip
}

在Visual Studio中,我要进行编译,结果是没有运算符采用Thing的左侧参数,然后如果我指定thing2->operator+(&tempThing); 那么它起作用了,这是令人困惑的,因为它应该仅依靠语言解析来解析该操作符功能

如果存在Class operator#(Class)函数,并且可以将参数转换为适当的类型,则只需使用运算符,然后编译器将其替换为operator函数,或者至少调用操作员功能。

thing1 = thing2 + thing3;   // written line 
thing1.operator=(thing2.operator+(thing3));

为什么我必须指定运算符功能。 编译器不应该为我这样做。

编辑:这是关于一般行为的问题,而不是代码的实际正确性。 即使当我出于某些原因编写语句时,也必须指定实际的operator()而不是仅仅使用符号。 (我不得不使用直接的示例以及逐个字符地复制字符,但这有时确实可行)

Thing tempThing();

这可能不是您想的那样。 谷歌的“最烦人的解析”。

thing1 = thing2 + &tempThing;

由于您的operator+引用(而不是指针),因此您不想使用该地址。 修改完前面的定义后,它应该可以编译为thing1 = thing2 + tempThing;

但是,一般而言,您要避免使用成员函数来使大多数运算符重载。 问题在于这样做允许将右操作数转换为正确的类型,但不能转换为左操作数。 通过使用全局重载,您可以获得对称性-可以转换任何一个操作数。

这是常见的款式有operator+operator-等等,你的类或类和朋友的功能operator+=operator-= ......,作为一个成员函数。 这是因为后面的对象正在修改对象本身,而第一个对象正在处理两个对象并返回第三个对象。 这是字符串类的示例代码,可能类似于:

class string {
public:
        string& operator+=(const string& other)
        {
                this->append(other);
                return *this;
        }
private:
        void append(const string& other)
        {
                // concatenate two strings here
        }
};

string operator+(const string& first, const string& second)
{
        string result(first);
        result += second;
        return result;
}

您的情况换线

Thing tempThing();  
thing1 = thing2 + &tempThing;

Thing tempThing;  
thing1 = thing2 + tempThing;

应该也可以。

您正在添加函数的指针

Thing tempThing();
thing1 = thing2 + &tempThing;

Thing tempThing(); 声明一个返回Thing, Thing tempThing; 创造事物

也:

operator==, operator+

应该是const

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM