C++ 中运算符使用哪种重载?

Geo*_*bor 3 c++ operator-overloading operators

每个人都知道不能使用 + 运算符连接 2 个字符串文字。

#include <iostream>

int main() {
  std::cout << "hello " + "world";
}
// Error
Run Code Online (Sandbox Code Playgroud)

这里发生的事情是你试图添加 2 char* 这是一个错误。但是,您可以将字符串文字添加到 std::string。

#include <iostream>

int main() {
  std::string s = "hello ";
  std::cout << s + "world";
}
// Fine, prints hello world
Run Code Online (Sandbox Code Playgroud)

但我发现下面的代码也是有效的。

#include <iostream>

int main() {
  std::string s = "world";
  std::cout << "hello " + s;
}
// Fine, prints hello world
Run Code Online (Sandbox Code Playgroud)

我想在上面的例子中,您正在尝试将 std::string 添加到 char* 但它工作正常。我认为它可能只是使用 + 运算符的 std::string 重载。我的问题是这里到底发生了什么,以及在诸如将两个具有完全有效的重载的不同类添加在一起的情况下,操作员如何决定使用哪个重载。

eer*_*ika 8

这里发生的事情是你试图添加 2 char* 这是一个错误。

更正确的是,您尝试添加两个数组,每个数组都会衰减到const char*.


我的问题是这里到底发生了什么

您正在使用这些重载:

std::string
operator+(const std::string& lhs, const char* rhs);

std::string
operator+(const char* lhs, const std::string& rhs);
Run Code Online (Sandbox Code Playgroud)

操作员如何决定使用哪个重载

它使用与普通函数相同的重载分辨率。由于重载解析非常复杂,因此完整而精确的描述不适合此答案。

简而言之:有一个所有同名函数的列表。这是过载设置。如果所有参数(运算符重载情况下的操作数)都可以转换为函数的形式参数,则该函数是重载决策的可行候选者。候选人按照一套规则进行排名。需要“较少”转化的候选者排名较高。如果一位候选人毫无疑问是排名最高的候选人,则将调用该超载;否则就会出现错误。