C++ 复数类,设计判两个复数对象是否相等和是否不相等的运算符。

来源:百度知道 编辑:UC知道 时间:2024/07/03 11:18:09
友元和运算符重载
基本内容:对复数类,设计判两个复数对象是否相等和是否不相等的运算符。
基本要求:
(1)运算符重载为类的成员函数。
(2)运算符重载为类的友元函数。
(3)分别设计测试主函数进行测试。

其他的照猫画虎

#include <iostream>

using namespace std;

class CComplex
{
private:
float real, image;
public:
CComplex() { }
CComplex( float r, float img ) { real = r; image = img; }
CComplex( CComplex& another )
{
real = another.real;
image = another.real;
}
bool operator==( CComplex& another )
{
if( real == another.real && image == another.image ) return true;
return false;
}
friend bool operator != (CComplex& c1, CComplex& c2)
{
if( c1.real != c2.real || c1.image != c2.image ) return true;
return false;
}
};

void main()
{
CComplex c1( 2, 3 ), c2( 2, 3 ), c3( 3, 3 );

if( c1 == c2 ) cout<<"equal"<<endl;
if( c1 != c3 ) cout<<"not equal"<<endl;
}