内置类型的运算符函数
Operator functions for built-in types
如何为内置类型定义的运算符显式使用基础运算符函数?请参阅代码:
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 算子函数应为非静态成员函数或 是至少有一个参数的非成员函数,其类型为 类、对类的引用、枚举或对 列举。
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载运算符new[]的行为取决于析构函数
- 构造函数和转换运算符之间的重载解析
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 是什么让一些命名函数/运算符与众不同?
- 删除了所有自动生成的构造函数/运算符的类仍然可以从函数返回吗
- 如何在局部类中定义友元函数运算符>>?
- 隐式转换和函数运算符
- 如何从函数运算符(x,y)返回向量元素的引用
- C++/析构函数-运算符删除
- 获取函数运算符<未定义的引用
- VS2012 std::函数运算符 bool 意外返回 true
- "Polymorphic"非成员函数/运算符,是否需要额外的重载?
- Xcode - 控制到达非无效函数运算符错误的末尾
- 重载类函数运算符兼任二传手和吸气手
- 为简单结构定义哪个复制/移动构造函数/运算符
- 关于函数/运算符重载的困惑
- 函数运算符上的未定义引用>>
- C++ 重载函数运算符和继承,无法在子类函数中正确使用它
- 如何使用另一个类的重载函数运算符(operator())