您的位置:首页 > 其它

基类与派生类对象的关系

2011-01-09 17:32 204 查看
#include <iostream>

using namespace std;

class A
{
int a;
public:
void setA(int x) {a=x;}
int getA() {return a;}
};

class B:public A
{
int b;
public:
void setB(int x) {b=x;}
int getB() {return b;}
};

void f1(A a,int x) {a.setA(x);}
void f2(A *pA,int x) {pA->setA(x);}
void f3(A &rA,int x) {rA.setA(x);}

void main()
{
A a1,*pA;
B b1,*pB;
a1.setA(1);
b1.setA(2);
a1=b1;
cout<<a1.getA()<<endl;
cout<<b1.getA()<<endl;
a1.setA(10);
cout<<a1.getA()<<endl;
cout<<b1.getA()<<endl;
pA=&b1;
pA->setA(20);
cout<<pA->getA()<<endl;
cout<<b1.getA()<<endl;
A &ra=b1;
ra.setA(30);
cout<<pA->getA()<<endl;
cout<<b1.getA()<<endl;
b1.setA(7);
cout<<b1.getA()<<endl;
f1(b1,100);
cout<<b1.getA()<<endl;
f2(&b1,200);
cout<<b1.getA()<<endl;
f3(b1,300);
cout<<b1.getA()<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: