继承成员函数访问数据成员
考虑下面的示例代码:
#include <iostream>
using namespace std;
class A
{
private:
static int a;
int b;
protected:
public:
A() : b(0) {}
void modify()
{
a++;
b++;
}
void display()
{
cout << a <<"\n";
cout << b <<"\n";
}
};
int A::a=0;
class B : public A {
private:
int b;
public:
B(): b(5)
{
}
};
int main()
{
A ob1;
B ob2;
ob1.display();
ob2.display();
return 0;
}
在上面的代码中,class A
有一个私有数据成员 b
,class B
也有一个私有数据成员b
。函数display()
用于显示数据成员。 当我使用ob1.display()调用display()时,display()访问A类的私有数据成员b。我明白这一点。但是,当我使用 ob2.display 调用显示时,display() 会访问哪个 b
?是A类的b
还是B类的b
?请解释为什么它访问类A的b
或类B的b
Consider the sample code below:
#include <iostream>
using namespace std;
class A
{
private:
static int a;
int b;
protected:
public:
A() : b(0) {}
void modify()
{
a++;
b++;
}
void display()
{
cout << a <<"\n";
cout << b <<"\n";
}
};
int A::a=0;
class B : public A {
private:
int b;
public:
B(): b(5)
{
}
};
int main()
{
A ob1;
B ob2;
ob1.display();
ob2.display();
return 0;
}
In the code above, the class A
has a private data member b
and class B
also has a private data member b
. The function display()
is used to display the data members.
When i invoke display() using ob1.display()
, display() accesses the private data member b
of class A. I understand that. But when i invoke display using ob2.display
, which b
does display() access? Is it the b
of class A or b
of class B? Kindly explain the why it accesses class A's b
or class B's b
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它将访问
A::b
。A
类中的display
方法实现根本不知道B::b
的存在,更不用说使用它了。出于所有意图和目的,B::b
与A::b
是分开的。仅在B
本身范围内,名称冲突使b
引用B::b
,隐藏A::b< /代码>。成员变量不能是
虚拟
。It will access
A::b
. Thedisplay
method implementation in classA
has no clue about the existence ofB::b
at all, let alone using it. For all intents and purposes,B::b
is separate fromA::b
. Only in the scope ofB
itself, the name conflict makesb
refer toB::b
, hidingA::b
. Member variables cannot bevirtual
.ob2.display()
将访问派生类成员。成员函数调用始终在
this
上求值,this->display()
如果this
指向基类的对象,并且因此,display()
函数内对b
的任何引用都会被评估为this->b
,即b
基类的。这是因为基类的
display()
不知道是否有任何其他类派生自它。基类始终独立于派生类。为了解决问题,遵循的通用模式是在派生类中提供一个display()
方法,然后该方法依次调用基类的dsiplay()
方法。ob2.display()
will access the derived class member.The member function call is always evaluated on
this
,this->display()
thethis
in case points to object of your Base class and hence any reference tob
inside thedisplay()
function is evaluated asthis->b
which isb
of the Base class.This is because
display()
of the Base class has no knowledge of whether any other class derives from it. Base class is always independent of the Derived class. To solve a problem the uual pattern followed is to provide adisplay()
method in the Derived class which then in turn calls thedsiplay()
method of the Base class.它是
A
类。A::display()
无法访问 B 私有成员。It is class
A
.A::display()
cannot access B private members.