一、
1.graph.h
class Graph{public: //公共端接口 Graph (char ch, int n); //构造函数 void draw(); //绘制图形private: //私有端接口 char symbol; int size;};
2.graph.cpp
// 类graph的实现 #include "graph.h" #includeusing 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=size-i-1;j>=0;j--) { cout<<" ";}for (int j=1;j<=i*2-1;j++){ cout< <
3.main.cpp
#include#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; }
运行结果
二、
1.Fraction.h
class Fraction{public: Fraction(); //构造函数 Fraction(int i,int j); //函数的重载 Fraction (int i); //函数的重载 void show(); //输出 void addition(Fraction &a); //加法函数 void minus(Fraction &a); //减法函数 void multiply(Fraction &a); //乘法 void divide(Fraction &a); //除法 void compare(Fraction &a); //比较private: int top; //分子 int bottom; //分母};
2.Fraction.cpp
#includeusing namespace std;Fraction::Fraction():top=0, bottom=1 {} //构造函数 Fraction::Fraction(int t0):top=t0, bottom=1 {} //重载 Fraction::Fraction(int t0,int b0):top=t0, bottom=b0{} //重载 void void Fraction::addition(Fraction &a){ Fraction b; b.top = top * a.bottom + a.top*bottom; b.bottom = bottom * a.bottom; b.show();} //加void Fraction::minus(Fraction &a){ Fraction b; b.top = top * a.bottom - a.top*bottom; b.bottom = bottom * a.bottom; b.show();} //减void Fraction::multiply(Fraction &f1){ Fraction f2; f2.top =top*f1.top; f2.bottom =bottom*f1.bottom; f2.show();} //乘void Fraction::divide(Fraction &a) { Fraction b; b.top =top*a.bottom; b.bottom = bottom *a.top; b.show();} //除void Fraction::compare(Fraction &a) { Fraction b; b.top = top * a.bottom - a.top*bottom; b.bottom = bottom * a.bottom; if(b.bottom*b.top > 0){ cout << top << "/" << bottom << ">" < << "/" << a.bottom <
3.main.cpp
#include#include "Fraction.h"using namespace std;int main() { Fraction a; Fraction b(3,4); Fraction c(5); a.show(); b.show(); c.show(); c.addition(b); c.minus(b); c.multiply(b); c.divide(b); c.compare(b); return 0;}