您的位置:首页 > 其它

继承中的同名成员变量和函数

2016-08-23 15:41 585 查看
同名成员函数

#include <iostream>
using namespace std;

class A
{
public:
int a;
int b;
public:
void get()
{
cout<<"b "<<b<<endl;
}
void print()
{
cout<<"AAAAA "<<endl;
}
protected:
private:
};

class B : public A
{
public:
int b;
int c;
public:
void get_child()
{
cout<<"b "<<b<<endl;
}
void print()
{
cout<<"BBBB "<<endl;
}
protected:
private:
};

int main()
{
B b1;
b1.print();

b1.A::print();
b1.B::print(); //默认情况

return 0;
}






同名成员变量
#include <iostream>
using namespace std;

class A
{
public:
int a;
int b;
public:
void get()
{
cout<<"b "<<b<<endl;
}
void print()
{
cout<<"AAAAA "<<endl;
}
protected:
private:
};

class B : public A
{
public:
int b;
int c;
public:
void get_child()
{
cout<<"b "<<b<<endl;
}
void print()
{
cout<<"BBBB "<<endl;
}
protected:
private:
};

//同名成员变量
int main()
{

B b1;
b1.b = 1; //修改的是子类的b
b1.get_child();
b1.get();

b1.A::b = 100; //修改父类的b
b1.B::b = 200; //修改子类的b 默认情况是B

b1.get();
b1.get_child();

cout<<"hello..."<<endl;
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐