重载二进制操作的正确方法
The proper way to overload binary operation
我是C++新手,所以,请放轻松:)我发现了两种不同的方法来重载 c++ 中的二进制运算符。
第一个(来自Robert Lafore的"面向对象编程C++"一书(:
class Distance
{
private:
int value;
public:
Distance() : value(0) {}
Distance(int v) :value(v) {}
Distance operator+(Distance) const;
};
Distance Distance::operator+(Distance d2) const
{
return Distance(value+d2.value);
}
另一个,使用朋友功能(来自互联网(
class Distance
{
private:
int value;
public:
Distance() : value(0) {}
Distance(int v) :value(v) {}
friend const Distance operator+(const Distance& left, const Distance& right);
};
const Distance operator+(const Distance& left, const Distance& right)
{
return Distance(left.value + right.value);
}
所有这些情况都可以编写如下代码:
Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2;
我的问题:这些案例的主要区别是什么?也许有一些优点或缺点。还是某种"良好的编程礼仪"?
提前感谢您的智慧! :)
Distance
可以从int
隐式转换。然后,第二种样式可以将opeartor+
与用作右操作数的对象一起使用Distance
。
Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2; //fine
Distance d4 = d1 + 5; //fine
Distance d5 = 5 + d1; //fine
第 1 种样式仅支持将 opeartor+
与用作左操作数的 Distance
对象一起使用。
Distance d1(11);
Distance d2(5);
Distance d3 = d1 + d2; //fine
Distance d4 = d1 + 5; //fine
Distance d5 = 5 + d1; //fail
有几个细微的区别,包括:
非会员方式允许两者兼而有之
42 + Distance(42);
Distance(42) + 42;
而会员方式只允许
Distance(42) + 42;
相关文章:
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 将位字符串转储到二进制文件的最佳方法是什么
- 在打印方法中,难以在二进制树中打印数据
- 读取二进制文件的惯用C++17标准方法是什么
- 从包含 IP 标头片段的二进制文件中读取结构的最佳方法是什么
- 使用 openssl 构建静态二进制文件的正确方法是什么?
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- 使用二进制参数调用LUA方法
- 设置用G 构建的二进制版本的任何方法
- C/C++ 方法中最快/最短计算二进制数字总和/又名二进制中的 1 数
- 是否有一种跨平台的方法可以在使用 C++ 编写的二进制应用程序中嵌入资源?
- 重载二进制操作的正确方法
- 在C 中对二进制对象进行编码/解码的标准方法
- 有没有一种优雅的方法来读取二进制文件并将其内容复制到向量<int>
- 从二进制缓冲区初始化变量的正确方法是什么
- g++ - 虚拟方法在生成的二进制中创建符号,我无法隐藏
- 保证C++库二进制兼容性的简单方法,C链接
- 一半填充二进制搜索树进行测试的最佳方法
- 一种将二进制文件读入犰狳矩阵的直接方法
- 在运行时动态更新二进制文件(可执行文件)而不停止的任何类型的方法