我有以下代码:
#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)
进行计算:
- 'a' 转换为 int
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
被提升为 int
或unsigned int
通过整数提升规则,然后将适当的转换应用于另一个操作数。 (通常情况下,双方都将以 int
结束,尽管您可以设计出 unsigned int
的平台。)
关于c++ - 当我将 int 添加到 char ('a' + 1 时调用哪个 operator+ 函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22467472/