运算符重载和非成员函数 C++
operator overloading and non-member functions c++
我已经为复数编写了一个类,其中我重载了运算符 +,一切正常,但是我需要将其实现为非成员函数,我不确定如何,或者为什么这样做有好处。
这是我的代码.h:
class Complex
{
private:
double a;
double b;
public:
Complex();
Complex(double aGiven);
Complex(double aGiven, double bGiven);
double aGetValue();
double bGetValue();
double operator[](bool getB);
Complex add(Complex &secondRational);
Complex operator+(Complex &secondRational);
}
。.cpp:
Complex Complex::add(Complex &secondRational)
{
double c = secondRational.aGetValue();
double d = secondRational.bGetValue();
double anew = a+c;
double bnew = b+d;
return Complex(anew,bnew);
}
Complex Complex::operator+(Complex &secondRational)
{
return add(secondRational);
}
有关如何将这些作为非成员功能的任何帮助将不胜感激!
下面是类外的加法运算符:
Complex operator+(const Complex& lhs, const Complex& rhs) {
//implement the math to add the two
return Complex(lhs.aGetValue() + rhs.aGetValue(),
lhs.bGetValue() + rhs.bGetValue());
}
当然,您需要将aGetValue()
和bGetValue()
声明为const
:
double aGetValue() const {return a;}
double bGetValue() const {return b;}
算术运算的常用方法是将运算符的自反版本定义为成员,将纯版本定义为非成员,并使用自反版本实现它们:
class complex {
public:
const complex& operator+=(const complex& rhs) {
real += rhs.real;
imag += rhs.imag;
return *this;
}
};
complex operator+(const complex& lhs, const complex& rhs) {
complex res(lhs);
res += rhs;
return res;
}
pippin1289 上面是如何解释的。
原因解释如下:
想象一下,需要使用类的对象作为
Complex c3 = 5 + c1;// for c3 object c1's real part (a) added with 5
作为C++保持操作数的顺序。编译器解析上述加法调用为5.operator+ (const Complex & other(;//这是不可能的因此,通过自由功能使其过载。
您的类通过公共接口(如 aGetValue(( 和 bGetValue(公开必要的信息。因此,这个免费的重载+运算符函数不一定是类的朋友。
此外,首选非友元非成员函数而不是成员函数,因为它有助于降低封装程度。这里解释了这一点==> http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197?pgno=1
您可以向Complex
类声明好友
class Complex {
// blah....
friend Complex operator+(Complex const& a, Complex const & b);
};
重载的运算符可以访问 Complex 的私有成员。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗