C++ 从子类方法访问基类变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6187020/
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
Access Base class variable from child class method
提问by Mattia
How can I access base class variable from a child method? I'm getting a segmentation fault.
如何从子方法访问基类变量?我遇到了分段错误。
class Base
{
public:
Base();
int a;
};
class Child : public Base
{
public:
void foo();
};
Child::Child() :Base(){
void Child::foo(){
int b = a; //here throws segmentation fault
}
And in another class:
在另一堂课中:
Child *child = new Child();
child->foo();
回答by Kanopus
It's not good practice to make a class variable public. If you want to access a
from Child
you should have something like this:
将类变量设为 public 并不是一个好习惯。如果您要访问a
的Child
,你应该有这样的事情:
class Base {
public:
Base(): a(0) {}
virtual ~Base() {}
protected:
int a;
};
class Child: public Base {
public:
Child(): Base(), b(0) {}
void foo();
private:
int b;
};
void Child::foo() {
b = Base::a; // Access variable 'a' from parent
}
I wouldn't access a
directly either. It would be better if you make a public
or protected
getter method for a
.
我也不会a
直接访问。如果你犯了一个会更好public
或protected
为getter方法a
。
回答by hackworks
class Base
{
public:
int a;
};
class Child : public Base
{
int b;
void foo(){
b = a;
}
};
I doubt if your code even compiled!
我怀疑您的代码是否已编译!
回答by Mattia
Solved! the problem was that I was calling Child::foo() (by a signal&slot connection) from a non yet existing object.
解决了!问题是我从一个尚不存在的对象调用 Child::foo() (通过信号和插槽连接)。
Thanks for the aswers.
感谢您的回答。