c++继承方式
公有继承,父类的私有成员不可访问,通过父类的公有函数以及保护函数访问
私有继承,父类成员在派生类中为私有成员等。
初始化顺序先父类,再是派生类,析构刚好相反,
当用父类指针或者引用实现多态时,析构函数要声明成虚函数,不然只会调用父类的析构函数
#include <iostream>
using namespace std;
class base{
private :float x;
public :base(float a){
cout<<"base init"<<endl;
x=a;
}
virtual void fun(float a){
cout<<"fun base"<<a<<endl;
}
void g(int a){
cout<<"g base"<<a<<endl;
}
~base(){
cout<<"base detele "<<endl;
}
};
class son :public base{
private : int s;
public :
son(float a,int b):base(a),s(b){
cout<<"son init"<<endl;
}
void fun(float a){
cout<<"fun son"<<a<<endl;
}
void g(int a){
cout<<"g son"<<a<<endl;
}
~son(){
cout<<"son delete"<<endl;
}
};
int main(){
float a=3.14;
float b=2.56;
int d=1;
int c=8;
base *p;
son test1(a,d);
base &p2= son(a,d);
//delete p2;
son *p1=&test1;
p=&test1;
p1->fun(b);
p1->g(c);
p->fun(b);
p->g(a);
p2.fun(b);
p2.g(a);
// getchar();
return 0;
}
c++ 复数类以及operator 重载输入 加法,乘法
#include<iostream>
using namespace std;
class complax{
private: int real;
int image;
public :
complax(){
real=0;
image=0;
}
complax(int r,int image){
real=r;
this->image=image;
}
void set_init(int r,int i){
real=r;
image=i;
}
void show(){
cout<<real;
if(image>=0)
cout<<"+"<<image<<"i"<<endl;
else
{
cout<<image<<"i"<<endl;
}
}
//重载+
complax operator +(const complax &t){
return complax(this->real+t.real,this->image+t.image);
}
//重载输入,只能是友元,为什么?因为cin对象为系统的对象没有this指针,不能通过对象来调用
//只能重载为友元函数或者是类外的普通的函数
friend istream &operator >>(istream &in,complax &a){
int r,i;
in>>r>>i;
a.real=r;
a.image=i;
return in;
}
//(a+bi)(c+di)=(ac-bd)+(bc+ad)i
friend complax operator*(const complax &a,const complax &b){
int r;
int i;
r=a.real*b.real-a.image*b.image;
i=a.image*b.real+a.real*b.image;
return complax(r,i);
}
};
void main(){
complax a;
complax b;
a.show();
cin>>a>>b;
a.show();
b.show();
complax c=a+b;
c.show();
complax d=a*b;
d.show();
}