C++ 调用父方法并访问父类中的私有变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4009505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling Parent methods and accessing private variable in a Parent class?
提问by mike_b
I'm trying to get the following code to work, but I can't find good-enough documentation on how C++ handles public vs. private inheritance to allow me to do what I want. If someone could explain why I can't access Parent::setSize(int)
or Parent::size
using private inheritance or Parent::size
using public inheritance. To solve this, to I need a getSize()
and setSize()
method in Parent?
我试图让下面的代码工作,但我找不到足够好的文档来说明 C++ 如何处理公共和私有继承来让我做我想做的事。如果有人可以解释为什么我不能访问Parent::setSize(int)
或Parent::size
使用私有继承或Parent::size
使用公共继承。为了解决这个问题,我需要在 Parent 中使用getSize()
andsetSize()
方法吗?
class Parent {
private:
int size;
public:
void setSize(int s);
};
void Parent::setSize(int s) {
size = s;
}
class Child : private Parent {
private:
int c;
public:
void print();
};
void Child::print() {
cout << size << endl;
}
int main() {
Child child;
child.setSize(4);
child.print();
return 0;
}
回答by Ned Batchelder
Change Parent to:
将父级更改为:
protected: int size;
If you want to access the size
member from a derived class, but not from outside the class, then you want protected
.
如果您想size
从派生类访问成员,而不是从类外部访问成员,那么您需要protected
.
Change Child to:
将子项更改为:
class Child: public Parent
When you say class Child: private Parent
, you are saying it should be a secret that Child is a Parent. Your main
code makes it clear that you want Child to be manipulated as a Parent, so it should be public inheritance.
当您说 时class Child: private Parent
,您是在说 Child 是 Parent 应该是一个秘密。您的main
代码清楚地表明您希望将 Child 作为 Parent 进行操作,因此它应该是公共继承。
回答by casablanca
When you use private inheritance, all public and protected members of the base class become private in the derived class. In your example, setSize
becomes private in Child
, so you can't call it from main
.
使用私有继承时,基类的所有公共成员和受保护成员在派生类中都变为私有。在您的示例中,在 中setSize
变为私有Child
,因此您不能从main
.
Also, size
is already private in Parent
. Once declared private, a member always remains private to the base class regardless of the type of inheritance.
此外,size
在Parent
. 一旦声明为私有,无论继承的类型如何,成员始终对基类保持私有。
回答by Bj?rn Pollex
回答by Aftonvegas
#include <iostream>
using namespace std;
class Parent {
private:
int size;
public:
void setSize(int s);
int fun() //member function from base class to access the protected variable
{
return size;
}
};
void Parent::setSize(int s) {
size = s;
}
class Child : private Parent {
private:
int c;
public:
void print();
using Parent::setSize; //new code line
using Parent::fun; //new code line
};
void Child::print() {
cout << fun() << endl;
}
int main() {
Child child;
child.setSize(4);
child.print();
return 0;
}