实验四
将4-20改成多文件格式
complex.h
#ifndef COMPLEX_H #define COMPLEX_H class Complex { public: Complex(double r0, double i0); Complex(double r0); Complex(Complex &c0); ~Complex(); void add(Complex &c0); void show(); private: double real, imaginary; }; #endif
complex.cpp
#include "Complex.h" #include <iostream> using namespace std; Complex::Complex(double r0, double i0):real(r0), imaginary(i0) { cout << "constructor Complex(double, double) is called. " << endl; } Complex::Complex(double r0):real(r0), imaginary(0) { cout << "constructor Complex(double) is called. " << endl; } Complex::Complex(Complex &c0):real(c0.real), imaginary(c0.imaginary) { cout << "copy constructor is called." << endl; } Complex::~Complex() { cout << "destructor is called." << endl; } void Complex::add(Complex &c0){ real += c0.real; imaginary += c0.imaginary; } void Complex::show() { if (imaginary > 0) cout << real << "+" << imaginary << "i" << endl; else if( imaginary == 0) cout << real << endl; else cout << real << imaginary << "i" << endl; }
main.cpp
#include <iostream> #include "Complex.h" using namespace std; int main(int argc, char** argv) { Complex c1(3,5); Complex c2(4.5); cout << "c1 = " ; c1.show(); cout << "c2 = " ; c2.show(); cout << "c1 + c2 = "; c1.add(c2); c1.show(); Complex c3(3,-2); c3.show(); return 0; }
2.graph
graph.cpp
// 类graph的实现 #include "graph.h" #include <iostream> using namespace std; // 带参数的构造函数的实现 Graph::Graph(char ch, int n): symbol(ch), size(n) { } // 成员函数draw()的实现 // 功能:绘制size行,显示字符为symbol的指定图形样式 // size和symbol是类Graph的私有成员数据 void Graph::draw() { for(int i=1;i<=size;i++) { for(int j=1;j<=size-i;j++) cout<<" "; //设置空格 for(int k=1;k<=2*i-1;k++) cout<<symbol; cout<<endl; } // 补足代码,实现「实验4.pdf」文档中展示的图形样式 }
graph.h
#ifndef GRAPH_H #define GRAPH_H // 类Graph的声明 class Graph { public: Graph(char ch, int n); // 带有参数的构造函数 void draw(); // 绘制图形 private: char symbol; int size; }; #endif
main.cpp
#include <iostream> #include "graph.h" using namespace std; int main() { Graph graph1('*',5), graph2('$',7) ; // 定义Graph类对象graph1, graph2 graph1.draw(); // 通过对象graph1调用公共接口draw()在屏幕上绘制图形 graph2.draw(); // 通过对象graph2调用公共接口draw()在屏幕上绘制图形 return 0; }