运算符未解析为运算符函数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)
函数,并且参数可以转换为适当的类型,那么所需要的就是使用运算符,编译器将用运算符函数替换它,或者至少调用运算符函数。
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
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 C++ 中调用类中的运算符函数
- 错误 C2676:std::set::const_iterator 没有运算符 + 函数?
- 为什么 ADL 的运算符函数行为与其他函数不同?
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 第二个常量在运算符函数中做什么?
- 重载赋值运算符函数和复制构造函数中的错误
- 内置类型的运算符函数
- 如何调用运算符函数添加两个对象?
- Const 仍然允许在运算符函数 c++ 下进行更改
- 在呼叫运算符函数const中调用运算符时错误
- 是否有一种方法可以在超载运算符函数中接触默认运算符函数
- 重载时获取堆栈溢出 >> 运算符函数是为类调用的。我需要进行哪些更改?
- 运算符 [] 函数的实现是如何工作的
- C++:使用父类运算符函数更新子类对象的继承变量
- 创建一个接受 2 个输入参数的文本运算符函数
- 为什么找不到重载运算符函数?
- 为什么auto_ptr中有模板复制构造函数和覆盖运算符函数
- 为什么某些C++标准库“运算符<<”函数将其流宽度重置为 0
- C++SFINAE运算符/函数结果类型检查