访问派生类中的基类成员 [英] accessing a base class member in derived class
问题描述
我有一个简单的类如下
class A {
protected:
int x;
};
class B:public A
{
public:
int y;
void sety(int d)
{
y=d;
}
int gety(){ return y;}
};
int main()
{
B obj;
obj.sety(10);
cout<<obj.gety();
getch();
}
因为变量A :: x具有受保护的访问权限,如果我想访问该类中的变量,并设置一个值,而不创建一个对象A.Is是可能的如果是,那么如何?
since the variable A::x has protected access and if i want to access that variable in class B and set a value to it without creating an object of A.Is it possible?if yes then how?
编辑:我们可以访问的值A :: x使用B的对象像obj.x
can we access the value of A::x using the object of B?like obj.x
推荐答案
B
是 A
,因此创建 B
的实例正在创建一个实例的 A
。也就是说,我不知道你的实际问题是什么,所以这里有一些代码,希望澄清的事情:
B
is an A
, so creating an instance of B
is creating an instance of A
. That being said, I'm not sure what your actual question is, so here's some code that will hopefully clarify things:
class A
{
protected:
int x;
};
class B : public A
{
public:
int y;
int gety() const { return y; }
void sety(int d) { y = d; }
int getx() const { return x; }
void setx(int d) { x = d; }
};
int main()
{
B obj;
// compiles cleanly because B::sety/gety are public
obj.sety(10);
std::cout << obj.gety() << '\n';
// compiles cleanly because B::setx/getx are public, even though
// they touch A::x which is protected
obj.setx(42);
std::cout << obj.getx() << '\n';
// compiles cleanly because B::y is public
obj.y = 20;
std::cout << obj.y << '\n';
// compilation errors because A::x is protected
obj.x = 84;
std::cout << obj.x << '\n';
}
obj
可以,因为
obj $ c>的实例
A :: x
$ c>隐含地是 A
的实例。
obj
can access A::x
just as an instance of A
could, because obj
is implicitly an instance of A
.
这篇关于访问派生类中的基类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!