问题
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();
回答1:
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:
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
.
回答2:
class Base
{
public:
int a;
};
class Child : public Base
{
int b;
void foo(){
b = a;
}
};
I doubt if your code even compiled!
回答3:
Solved! the problem was that I was calling Child::foo() (by a signal&slot connection) from a non yet existing object.
Thanks for the aswers.
来源:https://stackoverflow.com/questions/6187020/access-base-class-variable-from-child-class-method