課堂練習

WXD380yyds發表於2024-10-18

Complex.h中的程式碼:

#include <iostream>
#pragma once
class Complex
{
public:
	Complex(double x=0, double y=0);
	Complex(const Complex& p);
	~Complex();
	void add(const Complex& p);
	double get_real() const;
	double get_imag() const;
	friend Complex add(const Complex& p1, const Complex& p2);
	friend bool is_equal(const Complex& p1, const Complex& p2);
	friend bool is_not_equal(const Complex& p1, const Complex& p2);
	friend void output(const Complex& p);
	friend double abs(const Complex& p);
	static const std::string doc;
private:
	double real, imag;
};

Complex.cpp中的程式碼:

#include "Complex.h"
#include <cmath>
double Complex::get_real() const
{
	return real;
}
double Complex::get_imag() const
{
	return imag;
}
void Complex::add(const Complex& p)
{
	real = real + p.real;
	imag = imag + p.imag;
}
Complex::Complex(double x, double y):real{x},imag{y}{}
Complex::Complex(const Complex& p):real{ p.real },imag{ p.imag }{}
Complex::~Complex(){}
Complex add(const Complex& p1, const Complex& p2)
{
	return Complex(p1.real + p2.real, p1.imag + p2.imag);
}
bool is_equal(const Complex& p1, const Complex& p2)
{
	if (p1.real == p2.real && p1.imag == p2.imag)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
bool is_not_equal(const Complex& p1, const Complex& p2)
{
	if (p1.real == p2.real && p1.imag == p2.imag)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}
void output(const Complex& p)
{
	if (p.imag >= 0)
	{
		std::cout << p.real << " + " << p.imag << "i";
	}
	else
	{
		std::cout << p.real <<  " - " <<(-1.0)*p.imag << "i";
	}
}
double abs(const Complex& p)
{
	return sqrt(p.real * p.real + p.imag * p.imag);
}
const std::string Complex::doc{ "a simplfified Complex class" };

  

main.cpp中的程式碼:

// 待補足(多檔案組織程式碼時,需要包含的標頭檔案)
#include <iostream>
#include "Complex.h"
using std::cout;
using std::endl;
using std::boolalpha;

void test() {
    cout << "類成員測試: " << endl;
    cout << Complex::doc << endl;

    cout << endl;

    cout << "Complex物件測試: " << endl;
    Complex c1;
    Complex c2(3, -4);
    const Complex c3(3.5);
    Complex c4(c3);

    cout << "c1 = "; output(c1); cout << endl;
    cout << "c2 = "; output(c2); cout << endl;
    cout << "c3 = "; output(c3); cout << endl;
    cout << "c4 = "; output(c4); cout << endl;
    cout << "c4.real = " << c4.get_real() << ", c4.imag = " << c4.get_imag() << endl;

    cout << endl;

    cout << "複數運算測試: " << endl;
    cout << "abs(c2) = " << abs(c2) << endl;
    c1.add(c2);
    cout << "c1 += c2, c1 = "; output(c1); cout << endl;
    cout << boolalpha;
    cout << "c1 == c2 : " << is_equal(c1, c2) << endl;
    cout << "c1 != c3 : " << is_not_equal(c1, c3) << endl;
    c4 = add(c2, c3);
    cout << "c4 = c2 + c3, c4 = "; output(c4); cout << endl;
}

int main() {
    test();
}

  

執行截圖:

注意事項:main.cpp檔案中包含的檔案應為“Complex.h“而不是”Complex.cpp“,這會導致標頭檔案的內容在每個包含它的.cpp檔案中重複編輯,從而造成重複定義的問題。

學習體會:學會友元函式的操作,有關返回值為Complex型別的做法。

相關文章