c++ - 有人可以为我澄清 C++ 中的运算符重载吗?

标签 c++

<分区>

#include <iostream>   
using namespace std; 
class Height 
{ 
public: 
int feet, inch; 
Height() 
{ 
feet = 0; 
inch = 0; 
}   
Height(int f, int i) 
{ 
feet = f; 
inch = i; 
}   
// Overloading (+) operator to perform addition of 
// two distance object using binary operator
Height operator+(Height& d2) // Call by reference 

运算符重载函数的参数是什么? h3 对象是否作为参数发送?

{
// Create an object to return 
Height h3;   

是否可以在运算符重载函数中创建新对象?

// Perform addition of feet and inches 
h3.feet = feet + d2.feet; 
h3.inch = inch + d2.inch; 
// Return the resulting object 
return h3; 
} 
};  
int main() 
{ 
Height h1(3, 7);   

创建第一个对象会自动将其关联到高度类的第一个成员构造函数吗?

Height h2(6, 1); 

创建第二个对象是否会自动将其关联到高度类的第二个成员构造函数?

Height h3;   
//Use overloaded operator 
h3 = h1 + h2; 
cout << "Sum of  Feet & Inches: " << h3.feet << "'" << h3.inch << endl; 
return 0; 
} 

最佳答案

重载运算符与普通成员函数没有任何不同。

其实就是写作

h1 + h2

相当于写

h1.operator+(h2)

第一个版本只是语法糖,第二个版本更清楚地告诉你到底发生了什么。

由于运算符与普通成员函数没有任何不同,因此您可以肯定地在函数内部创建一个新对象。正如已经指出的那样,这是 operator+ 的预期行为。

does creating a first object automatically associate it to the first member constructer of the height class ?

does creating a second object automatically associate it to the second member constructer of the height class ?

我不太明白你在这里问什么。
Height h1(3, 7); 将调用 Height(int f, int i) 构造函数,因为参数匹配。
Height h3; 将出于同样的原因调用 Height() 构造函数。

关于c++ - 有人可以为我澄清 C++ 中的运算符重载吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59112016/

相关文章:

c++ - 我可以告诉我的编译器忽略语句或函数的副作用吗?

c++ - 无法打印所有整数值

java - Android NDK - Gradle 构建错误

c++ - 如何使用 date.h 在 C++ 中获取当前星期几?

c++ - 消费者应用程序的安全 TCP 连接建议

c++ - 多线程性能

c++ - 在 C++ 中将未知类传递给字符串流

c++ - 如何实现方便的初始化?

c++ - 我应该使用 std::system 来编写单元测试的脚本部分吗?

C++ 分析和优化