c++ - 当我将 int 添加到 char ('a' + 1 时调用哪个 operator+ 函数)

标签 c++ casting operators

我有以下代码:

#include <iostream>
using namespace std;

int main()
{
  cout << ('a' + 1) << endl;
  cout << static_cast<char>('a' + 1) << endl;
  cout << static_cast<int>('a' + 1) << endl;
}

The output is:
98
b
98

我假设 'a' + 1 按以下顺序使用函数 int operator+(int, int) 进行计算:

  1. 'a' 转换为 int
  2. operator+ 返回整数结果 (98)

这都是我的预测。如何才能 100% 确定调用了哪个函数?

更新

更清晰的类型修改:

  cout << (typeid('a') == typeid(char) ? "char" : "not char") << endl;
  cout << (typeid(1) == typeid(int) ? "int" : "not int") << endl;
  cout << (typeid('a' + 1) == typeid(int) ? "int" : "not int") << endl;

The output is:
char
int
int

最佳答案

内置运算符构成基本表达式,不是函数调用。它们是核心语言的一部分。对于算术类型,应用了一组转换(“通常的算术转换”,5/9),以便两个操作数都是相同类型的值。在您的示例中,一个操作数是 char,另一个是 int,因此 char 被提升为 intunsigned int 通过整数提升规则,然后将适当的转换应用于另一个操作数。 (通常情况下,双方都将以 int 结束,尽管您可以设计出 unsigned int 的平台。)

关于c++ - 当我将 int 添加到 char ('a' + 1 时调用哪个 operator+ 函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22467472/

相关文章:

c++ - C++的子集和递归

c++ - 为什么使用 'cpp' 编译这个简单的 C++ 程序会失败?

c# - 编译时和运行时转换 c#

C#转换为小数

c++ - C++ 中 += 和 =+ 运算符的区别?

perl - 为什么 'print (52-80)*42' 与 Perl 中的 'print 42*(52-80)' 不同?

c++ - 将制表符和换行符分隔的 CSV 数据导入变量

C++ 通过引用或值传递指针

c++ - 将 shared_ptr<Derived> 作为 shared_ptr<Base> 传递

c++ - std::sort 和 std::unique 结构问题