# C++学习代码

1.重载运算符实现复数数据运算

#include<iostream>

using namespace std;
using std::cout;
using std::endl;

class Complex
{
private:
double real;
double image;
public:
Complex(double real=0.0,double image=0.0)
{
this->real=real;this->image=image;
}
void display()
{
cout<<"("<<real<<","<<image<<")"<<endl;
}
friend Complex operator +(Complex A,Complex B)
{
return Complex(A.real+B.real,A.image+B.image);
}
friend Complex operator -(Complex A,Complex B)
{
return Complex(A.real-B.real,A.image-B.image);
}
friend Complex operator -(Complex A)
{
return Complex(-A.real,-A.image);
}
friend Complex operator ++(Complex A)
{
return Complex(++A.real,A.image);
}
friend Complex operator ++(Complex A,int)
{
return Complex(A.real++,A.image);
}
};

int main()
{
int i;
Complex A(100.0,200.0),B(-10.0,20.0),C;
cout<<"A=",     A.display();
cout<<"B=",     B.display();
C=A+B;
cout<<"C=A+B=",C.display();
C=A-B;
cout<<"C=A-B=",C.display();
C=-A+B;
cout<<"C=-A+B=",C.display();
C=A++;
cout<<"C=A++=",C.display();
C=++A;
cout<<"C=++A=",C.display();
C=A+5;
cout<<"C=A+5=",C.display();
cin>>i;
}

2.虚函数实现动态联编

#include<iostream>

using namespace std;

class Point
{
private:
int X,Y;
public:
Point(int X=0,int Y=0)
{
this->X=X;this->Y=Y;
}
virtual double area()
{
return 0.0;
}
};

const double PI=3.14159;

class Circle:public Point
{
private:
public:
Circle(int X,int Y,double R):Point(X,Y)
{
}
double area()
{
}
};

int main()
{
int i;
Point P1(10,10);
cout<<"P1.area()="<<P1.area()<<endl;
Circle C1(10,10,20);
cout<<"C1.area()="<<C1.area()<<endl;
Point *pp;
pp=&C1;
cout<<"pp->area()="<<pp->area()<<endl;
Point &rp=C1;
cout<<"rp.area()="<<rp.area()<<endl;
cin>>i;
}

3.虚基类

#include<iostream>

using namespace std;

class Automobile
{
private:
int power;
public:
Automobile(int power)
{
this->power=power;
cout<<"Automobile constructing..."<<endl;
}
void show()
{
cout<<"  power:"<<power;
}
};

class Car:virtual public Automobile
{
private:
int seat;
public:
Car(int power,int seat):Automobile(power)
{
this->seat=seat;
cout<<"Car constructing..."<<endl;
}
void show()
{
cout<<"car";
Automobile::show();
cout<<"  seat:"<<seat<<endl;
}
};

class Wagon:virtual public Automobile
{
private:
public:
{
cout<<"Wagon constructing..."<<endl;
}
void show()
{
cout<<"Wagon";
Automobile::show();
}
};

class StationWagon:public Car,public Wagon
{
public:
{
cout<<"StationWagon constructing..."<<endl;
}
void show()
{
cout<<"StationWagon:"<<endl;
Car::show();
Wagon::show();
}
};

int main()
{
int i;
StationWagon  SW(105,108,3,8);
SW.show();
cin>>i;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：C++学习代码 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)