小编Geo*_*bor的帖子

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

每个人都知道不能使用 + 运算符连接 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 重载。我的问题是这里到底发生了什么,以及在诸如将两个具有完全有效的重载的不同类添加在一起的情况下,操作员如何决定使用哪个重载。

c++ operator-overloading operators

3
推荐指数
1
解决办法
129
查看次数

标签 统计

c++ ×1

operator-overloading ×1

operators ×1