实验结论
实验内容1
源码 main.cpp#include#include"chip.h"using namespace std;int main(){ int m,n; cout<<"输入两个数m,n"< >m>>n; Basic base(m,n); A a(m,n); B b(m,n); C c(m,n); base.add() ; a.add() ; a.sub() ; b.add() ; b.mul() ; c.add() ; c.div() ; return 0;}
chip.h
#includeusing namespace std;class Basic {public: Basic(int m0,int n0):m(m0),n(n0) {} int add() { cout << "m + n = " << m + n << endl; } int m, n;};class A : public Basic {public: A(int m0, int n0) : Basic(m0,n0) {} int sub() { cout << "m - n = " << m - n << endl; }};class B : public Basic {public: B(int m0, int n0) : Basic(m0,n0) {} int mul() { cout << "m * n = " << m * n << endl; }};class C : public Basic {public: C(int m0, int n0) : Basic(m0,n0) {} double div() { cout << "m / n = " << double(m) / n << endl; }};
截图
实验内容2 源码 main.cpp#include#include"vehicle.h" using namespace std;int main(){ Motorcycle mc(1,2,3,4); mc.run() ; mc.stop() ; return 0;}
vehicle.h
#includeusing namespace std;class Vehicle{ public: Vehicle(int m,int w):maxspeed(m),weight(w){} int maxspeed,weight; void run(){cout<<"run"<
截图
实验内容3 源码 main.cpp#include#include"fraction.h"using namespace std;int main(){ Fraction p1(3,5),p2(4,7),p3; p3=p1+p2; cout< <
fraction.h
#includeusing namespace std;class Fraction{ public: Fraction(){ } Fraction(int t0,int b0); friend Fraction operator+(const Fraction &p1,const Fraction &p2); friend Fraction operator-(const Fraction &p1,const Fraction &p2); friend Fraction operator*(const Fraction &p1,const Fraction &p2); friend Fraction operator/(const Fraction &p1,const Fraction &p2); friend ostream& operator<<(ostream &out,const Fraction &p); int top; int bottom;};class iFraction:public Fraction{ public: iFraction(){ } iFraction(int t0,int b0); void show();};
fraction.cpp
#include"fraction.h"#include#include using namespace std;int gys(int x,int y)//求最大公约数 { int m=1,a=x,b=y; for(;m!=0;) { m=a%b;a=b;b=m; } return a;}//Fraction类的实现int m;//m为分子分母最大公约数 int bottom,top;Fraction::Fraction(int t0,int b0):top(t0),bottom(b0){}//构造函数重载Fraction operator+(const Fraction &p1,const Fraction &p2){ bottom=p1.bottom*p2.bottom; top=p1.top*p2.bottom+p1.bottom*p2.top; m=gys(fabs(top),fabs(bottom)); top/=m,bottom/=m; return(Fraction(top,bottom)); }Fraction operator-(const Fraction &p1,const Fraction &p2){ bottom=p1.bottom*p2.bottom; top=p1.top*p2.bottom-p1.bottom*p2.top; m=gys(fabs(top),fabs(bottom)); top/=m,bottom/=m; return(Fraction(top,bottom));}Fraction operator*(const Fraction &p1,const Fraction &p2){ top=p1.top*p2.top,bottom=p1.bottom*p2.bottom; m=gys(fabs(top),fabs(bottom)); top/=m,bottom/=m; return(Fraction(top,bottom));}Fraction operator/(const Fraction &p1,const Fraction &p2){ top=p1.top*p2.bottom,bottom=p1.bottom*p2.top; m=gys(fabs(top),fabs(bottom)); top/=m,bottom/=m; return(Fraction(top,bottom));}ostream& operator<<(ostream &out,const Fraction &p){ out< <<"/"<
截图
实验总结与体会
基本掌握了运算符重载,同时了解到友元函数不属于类的成员,不能被继承