栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

类的多态性(C++)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

类的多态性(C++)

定义一个复数类Complex,重载运算符“+”、“-”、“*”、“~”“==”以及“<<”,使之能用于复数的加、减、乘、求反(虚部反)、比较和输出等运算。其中“+”“-”“~”重载为成员函数,“*”“==”“<<”重载为友元函数。

#include
using namespace std;
class Complex
{
private:
    double real;
    double imag;
public:
    Complex() { real = 0; imag = 0; };
    Complex(double r, double i) :real(r), imag(i) {};
    void display();
    Complex operator+(Complex c1);
    Complex operator-(Complex c1);
    Complex operator~();
    friend Complex operator* (Complex c1, Complex c2);
    friend ostream& operator <<(ostream& out, Complex& c);
    friend bool operator==(Complex&, Complex&);
};
void Complex::display()
{
    cout << "(" << real << "," << imag << "i)" << endl;
}
Complex Complex::operator+(Complex c1)
{
    Complex c;
    c.real = real + c1.real;
    c.imag = imag + c1.imag;
    return c;
}
Complex Complex::operator-(Complex c1)
{
    Complex c;
    c.real = real - c1.real;
    c.imag = imag - c1.imag;
    return c;
}
Complex Complex:: operator~()
{
    this->imag = 0 - this->imag;
    return *this;
}
Complex operator* (Complex c1, Complex c2)
{
    return Complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c1.imag + c2.real);
}
ostream& operator <<(ostream& out, Complex& c)
{
    out << "(" << c.real << "," << c.imag << "i)" ;
    return out;
}
bool operator==(Complex& c1, Complex& c2)
{
    if (c1.real == c2.real && c1.imag == c2.imag)
        return true;
    else
        return false;
}
int main()
{
    Complex c1(1, 2), c2(3, 4);
    cout << c1 << endl;
    cout << c2 << endl;
    (c1 + c2).display();
    (c2 - c1).display();
    (c1 * c2).display();
    (~c1).display();
    cout << (c1 == c2) << endl;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/913553.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号