
#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; }

#ifndef GRAPH_H #define GRAPH_H // 类Graph的声明 class Graph { public: Graph(char ch, int n); // 带有参数的构造函数 void draw(); // 绘制图形 private: char symbol; int size; }; #endif

// 类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() { // 补足代码,实现「实验4.pdf」文档中展示的图形样式 int line=-1; for(int n1=(size-1);n1>=0;n1--) { line+=2; //line为每行中字符的数量,相邻两行相差2 for(int n2=n1;n2>0;n2--) { cout<<' '; } for(int line1=line;line1>0;line1--) { cout<<symbol; } for(int n3=n1;n3>0;n3--) { cout<<' '; } cout<<endl; } }
思路:如输入n,那么字符一共有n行,每行 目标字符 数量 由1开始 每行加2;第一行第n个字符为目标字符,之前为空格;第二行第(n-1)个字符为目标字符;因此输出分三部分,关于目标字符对称。第一部分为目标字符之前的空格,为(n-第x行);第二部分为目标字符,一共(2x行数-1);第三部分同第一部分

#include <iostream> #include "Fraction.h" /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { Fraction a(1); //a=1 Fraction b(3,4); //b= 3/4 Fraction c; // c=0 a.divide(b); a.compare(b); b.plus(c); a.show(); return 0; }

#ifndef FRACTION_H #define FRACTION_H class Fraction { public: Fraction(); Fraction(int t0); Fraction(int t0,int b0); void plus(Fraction &f); void minus(Fraction &f); void x(Fraction &f); void divide(Fraction &f); void compare(Fraction &f); void show(); private: int top; int bottom; }; #endif

#include "Fraction.h" #include <iostream> using namespace std; Fraction::Fraction():top(0),bottom(1) { cout<<"构造函数已调用(1),分数初始化"<<endl; } Fraction::Fraction(int t0):top(t0),bottom(1) { cout<<"构造函数已调用(2),分数初始化"<<endl; } Fraction::Fraction(int t0,int b0):top(t0),bottom(b0) { cout<<"构造函数已调用(3),分数初始化"<<endl; } void Fraction::plus(Fraction &f) { top*=f.bottom; top+=((f.top)*bottom); bottom*=f.bottom; cout<<"结果为 "<<top<<'/'<<bottom<<endl; } void Fraction::minus(Fraction &f) { top*=f.bottom; top-=((f.top)*bottom); bottom*=f.bottom; cout<<"结果为 "<<top<<'/'<<bottom<<endl; } void Fraction::x(Fraction &f) { top*=f.top; bottom*=f.bottom; cout<<"结果为 "<<top<<'/'<<bottom<<endl; } void Fraction::divide(Fraction &f) { top*=f.bottom; bottom*=f.top; cout<<"结果为 "<<top<<'/'<<bottom<<endl; } void Fraction::compare(Fraction &f) { int thisone,thatone; thisone=top*f.bottom; thatone=bottom*f.top; if(thisone>thatone) { cout<<"前者大"<<endl; } else if(thisone==thatone) { cout<<"一样大"<<endl; } else { cout<<"后者大"<<endl; } } void Fraction::show() { cout<<top<<'/'<<bottom<<endl; }
第二题中的加减乘除貌似可以用函数重载做。我有时间再修改下;
要把程序分为三部分的话,最好还是放在一个源代码里先确定编译成功,再新建项目,分到三个文件中。这样可以让int main上的 类的实现放到其他文件中,让整个代码看起来更简洁