c++ - 重载运算符命令

标签 c++ operator-overloading

<分区>

Possible Duplicate:
Operator Overloading in C++ as int + obj
Operator overloading

我有一个带有此运算符的 Point 对象:

Point operator +(float other) const {
  return Point(x + other, y + other, z + other);
}

我可以像这样执行加法:

point + 10

但我不能以相反的顺序执行:

10 + point

是否需要重载另一个运算符才能提供此功能?

最佳答案

您通常希望重载全局 运算符:

Point operator+(Point const &a, float b);
Point operator+(float a, Point const &b);

您可能只想使用一个重载,而不是两个重载:

Point operator+(Point const &a, Point const &b);

然后有一个构造函数从一个 float 创建一个点:

class Point { 
    public:
        Point(float);
};

在这种情况下,将 float 添加到 Point 将使用构造函数将 float 转换为 Point,然后使用重载的 operator+ 将这两个 Point 相加。

关于c++ - 重载运算符命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7651954/

相关文章:

c++ - sqlite3_bind_text SQLITE_STATIC vs SQLITE_TRANSIENT for c++ string

arrays - 如何在 F# 中添加两个数值数组

c++ - 使用类模板的下标重载函数中的引用类型初始化无效

c++ - C++中两个/两个以上对象的重载加法赋值运算符?

c++ - 使用 c++1z 在 <functional> 上出现 clang 4 构建错误

c++ - 神经网络在用于处理数据之前似乎工作正常(所有结果几乎相同)

c++ - 如何防止g++优化由IRQ可以更改的变量控制的循环?

C++ 复制构造函数调用其他构造函数

c++ - 当重载为类的成员函数时,取消引用运算符 (*) 是如何工作的?

c++ - 过载解析的问题