基类派生类公有派生的情况下赋值兼…

来源:互联网 发布:淘宝商家怎么找客服 编辑:程序博客网 时间:2024/06/06 02:18
// 基类派生类公有派生的情况下赋值兼容规则

#include
using namespace std;

// 声明基类
class base{
private:
int a,b;
public:
base(int,int);
void get();
};


// 声明派生类
class child :public base {
private:
int x,y;
public:
child(int,int,int,int);
void get();
};


int main(){
base b(1,2);
child c(3,4,5,6);

b.get(); // a:1 , b:2
c.get(); // x:3 , y:4

// 派生类对象对基类对象赋值时,调用基类成员函数,使用派生类数据成员

base b1 = c;
b1.get(); // a:5 , b:6

base *b2 = &c;
b2->get(); // a:5 , b:6

base &b3 = c;
b3.get(); // a:5 , b:6

b = c;
b.get(); // a:5 , b:6


return 0;
}


// 定义类方法
base::base(int x,int y){
a=x;
b=y;
}
void base::get(){
cout<<"a:"<<a<<" ,"<<"b:"<<b<<endl;
}


child::child(int m,int n,int x,int y):base(x,y){ // 继承时继承函数参数不用加限定符,参数从child传过来
this->x=m;
this->y=n;
}
void child::get(){
cout<<"x:"<<x<<" ,"<<"y:"<<y<<endl;
}


原创粉丝点击