Mat*_*tia 8 c++ inheritance 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
}
Run Code Online (Sandbox Code Playgroud)
而在另一堂课:
Child *child = new Child();
child->foo();
Run Code Online (Sandbox Code Playgroud)
Kan*_*pus 21
将类变量公开是不好的做法.如果您要访问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
}
Run Code Online (Sandbox Code Playgroud)
我也不会a直接访问.如果你制作一个public或protectedgetter方法会更好a.