试设计一个复数类,该类有实部和虚部两个成员数据,成员数据采用私有访问权限,同时该类有两个公有成员函数,分别用来设置成员数据和输出成员数据。(采用多文件结构)
时间: 2024-05-08 16:16:07 浏览: 102
复数类头文件(complex.h):
```c++
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex {
public:
Complex(double real = 0.0, double imag = 0.0); // 构造函数
void set(double real, double imag); // 设置实部和虚部
void print() const; // 输出实部和虚部
private:
double m_real; // 实部
double m_imag; // 虚部
};
#endif
```
复数类源文件(complex.cpp):
```c++
#include "complex.h"
#include <iostream>
Complex::Complex(double real, double imag) : m_real(real), m_imag(imag) {}
void Complex::set(double real, double imag) {
m_real = real;
m_imag = imag;
}
void Complex::print() const {
std::cout << m_real << "+" << m_imag << "i" << std::endl;
}
```
测试程序源文件(main.cpp):
```c++
#include "complex.h"
int main() {
Complex c;
c.set(1.0, 2.0);
c.print();
return 0;
}
```
编译并运行测试程序:
```
$ g++ main.cpp complex.cpp -o main
$ ./main
1+2i
```
阅读全文