运算符未解析为运算符函数c++

operator not resolving to operator function c++

本文关键字:运算符 函数 c++      更新时间:2023-10-16

我一直在处理需要重载某些运算符的类(=、==、+、!=等)。我编写运算符函数,但有时它们没有被调用,或者编译器表现得好像它根本不存在。例如:

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)函数,并且参数可以转换为适当的类型,那么所需要的就是使用运算符,编译器将用运算符函数替换它,或者至少调用运算符函数。

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

为什么我必须指定运算符函数。编译器不应该为我做那件事吗?

编辑:这是一个关于一般行为的问题,而不是代码的实际正确性。即使在我编写语句时,由于某种原因,它们也必须指定实际的运算符(),而不是只能使用符号。(我不得不用直接的例子来做这件事,也必须逐个字符地复制,但有时它确实有效)

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;创建Thing

还有:

operator==, operator+

应该是const