内置类型的运算符函数

Operator functions for built-in types

本文关键字:函数 运算符 置类型 内置      更新时间:2023-10-16

如何为内置类型定义的运算符显式使用基础运算符函数?请参阅代码:

struct Int
{
Int() = default;
Int(int initial)
{
i = initial;
}
Int operator+(Int other)
{
return Int(i + other.i);
}
int i;
};
std::ostream& operator<< (std::ostream &out, const Int& data)
{
out << data.i;
return out;
}
int main()
{
Int a, b = 5, c = 5;
a = b + c;
std::cout << a << std::endl;
Int d, e = 5, f = 5;
d.operator=(e.operator+(f));  // possible with user defined types
std::cout << d << std::endl;
int g, h = 5, j = 5;
g.operator=(h.operator+(j));  // illegal
return 0;
}

标有"非法"的部分会产生以下错误:

请求成员 'H' 中的 'operator+',其非类类型为 'int'

我知道您不能在非类类型的 int 上调用方法。问题是运算符+的含义在哪里定义,以及是否可以显式使用它。

如何为内置类型定义的运算符显式使用基础运算符函数?

你不能。

如果您正在寻找标准的相关部分,那么它应该是:

16.5 重载运算符

6 算子函数应为非静态成员函数或 是至少有一个参数的非成员函数,其类型为 类、对类的引用、枚举或对 列举。