课堂练习
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类型的做法。
浙公网安备 33010602011771号