7-2 友元类Cvector 武汉理工大学

7-2 友元类Cvector
分数 19
作者 谢颂华
单位 武汉理工大学
定义复数类CComplex和二维向量类CVector。
复数类具有实部real和虚部imag,定义构造函数。
二维向量有两个向量x和y,定义转换函数Change()和输出显示函数Print()。
在类CComplex中定义友元类CVector,实现将复数转换为二维向量,即real 赋值给x、 imag赋值给y。

输入样例1:
输入复数的实部和虚部

1.2 3.4
输出样例1:
第一行输出复数的real和imag,第二行输出转换后的向量的x和y

complex:1.2+3.4i
vector:(1.2,3.4)
输入样例2:
输入复数的实部和虚部

1.2 -3.4
输出样例2:
第一行输出复数的real和imag,第二行输出转换后的向量的x和y

complex:1.2-3.4i
vector:(1.2,-3.4)

#include 
using namespace std;

class CVector; // 声明CVector类以便在CComplex类中使用

class CComplex {
private:
    double real;
    double imag;

public:
    CComplex(double r, double i) : real(r), imag(i) {}

    friend class CVector; // 声明CVector为CComplex的友元类

    void displayComplex() {
        cout << "complex:" << real << ((imag >= 0) ? "+" : "") << imag << "i" << endl;
    }
};

class CVector {
private:
    double x;
    double y;

public:
    CVector(CComplex &c) : x(c.real), y(c.imag) {}

    void displayVector() {
        cout << "vector:(" << x << "," << y << ")" << endl;
    }
};

int main() {
    double r, i;
    cin >> r >> i;

    CComplex complex(r, i);
    complex.displayComplex();

    CVector vector(complex);
    vector.displayVector();

    return 0;
}

你可能感兴趣的:(算法)