一、定义一个Graph类。
功能:
1.绘制倒三角的图形。
2.可设置尺寸和字体。
3.调整背景和文字底色。
#ifndef GRAPH_H
#define GRAPH_H
// 类Graph的声明
class Graph {
public:
Graph(char ch, int n); // 带有参数的构造函数
void draw(); // 绘制图形
void draw1();
void draw2();
void draw3();
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) {
cout << "The graph has created." << endl;
}
// 成员函数draw()的实现
// 功能:绘制size行,显示字符为symbol的指定图形样式
// size和symbol是类Graph的私有成员数据
void Graph::draw() {
int i, j;
for (i = 0;i < size;i++)
{
for (j = 1;j <size-i;j++)
{
cout << ' ';
}
for (int k = 0;k <= i*2;k++)
{
cout << symbol;
}
cout<<endl;
}
// 补足代码,实现「实验4.pdf」文档中展示的图形样式
}
void Graph::draw1() {
int i, j;
for (i = 0;i < size;i++)
{
for (j = 1;j <size-i;j++)
{
cout << ' ';
}
for (int k = 0;k <= i*2;k++)
{
cout << symbol;
system("color 1e");
}
cout<<endl;
}
}
void Graph::draw2() {
int i, j;
for (i = 0;i < size;i++)
{
for (j = 1;j <size-i;j++)
{
cout << ' ';
}
for (int k = 0;k <= i*2;k++)
{
cout << symbol;
system("color 84");
}
cout<<endl;
}
}
void Graph::draw3() {
int i, j;
for (i = 0;i < size;i++)
{
for (j = 1;j <size-i;j++)
{
cout << ' ';
}
for (int k = 0;k <= i*2;k++)
{
cout << symbol;
system("color f7");
}
cout<<endl;
}
}
#include <iostream>
#include "graph.h"
#include <windows.h>
using namespace std;
int main() {
int n;
char c;
Graph graph1('*',5);
graph1.draw1();
cout<<"Press enter to continue.";
getchar();//控制停顿 当按下enter后程序继续执行
system("cls");//将之前的内容清除
Graph graph2('$',7) ;
graph2.draw2();
cout<<"Press enter to continue.";
getchar();
system("cls");
cout<<"输入想绘制的图形与层数:";
cin>>c>>n;
Graph graph3(c,n);
graph3.draw3();
getchar();
return 0;
}
运行效果截图:
关于背景色的设置其实很容易
函数system("color xx")中 前为背景色后为字体颜色 只需组合一下便能生成想要的颜色了。