cplus 实验四
实验1,4—20重写
//类定义,Complex.h
class Complex {
public:
Complex( double at, double bt) :a(at),b(bt) {}
Complex( double at) {
a=at;
}
void add(Complex &num);
void show();
private:
double a,b;
};
//类实现,Complex.cpp
#include"Complex.h"
#include<iostream>
using namespace std;
void Complex::add(Complex &num) {
a=a+num.a;
b=b+num.b;
}
void Complex::show(){
cout<<a<<"+"<<b<<"i"<<endl;
}
//主函数,Complex.cpp
#include"Complex.h"
#include<iostream>
using namespace std;
int main(){
Complex c1(3,5);
Complex c2=4.5;
c1.add(c2);
c1.show();
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 i,j,k;
for(i=1;i<=size;i++){
for(j=1;j<=size-i;j++)
cout<<" ";
for(k=1;k<=2*i-1;k++)//每行1,3,5....个
cout<<symbol;
cout<<endl;}}
#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;
}

实验三
//文件1,类定义,fraction.h
class Fraction{
public:
Fraction(int t=0,int b=1);
void show();
void add(Fraction &num);
void jian(Fraction &num);
void chen(Fraction &num);
void chu(Fraction &num);
private:
int top;
int bottom;
};
//类实现,fraction.cpp
#include"fraction.h"
#include<iostream>
using namespace std;
Fraction::Fraction(int t,int b):top(t),bottom(b){
}
void Fraction::add(Fraction &num){
top=top*num.bottom+num.top*bottom;
bottom=bottom*num.bottom;
}
void Fraction::jian(Fraction &num){
top=top*num.bottom-num.top*bottom;
bottom=bottom*num.bottom;
}
void Fraction::chen(Fraction &num){
top=top*num.top;
bottom=bottom*num.bottom;
}
void Fraction::chu(Fraction &num){
top=top*num.bottom;
bottom=bottom*num.top;
}
void Fraction::show(){
cout<<top<<'/'<<bottom<<endl;
}
//文件三。主函数实现,main.cpp
#include"fraction.h"
#include <iostream>
using namespace std;
int main() {
Fraction a;
Fraction b(3,4);
Fraction c(5);
a.show();
b.show();
c.show();
a.add(b);
a.show();
b.jian(b);
b.show();
c.chen(c);
c.show();
c.chu(c);
c.show();
return 0;
}

结论:本次实验学习主要为学会创建项目,通过多文件形式运行一个项目。实验中当把构造函数的声明与实现同时写在.h文件下时,程序运行不了。通过本次实验学习,更加掌握了类的功能与实现,为编写大程序打好基础

浙公网安备 33010602011771号