从子类方法访问基类变量
Access Base class variable from child class method
如何从子方法访问基类变量?我有一个分割错误。
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
}
在另一个类别中:
Child *child = new Child();
child->foo();
公开类变量不是一个好的做法。如果你想从Child
访问a
,你应该有这样的东西:
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
}
我也不会直接访问a
。如果您为a
制作一个public
或protected
getter方法会更好。
class Base
{
public:
int a;
};
class Child : public Base
{
int b;
void foo(){
b = a;
}
};
我怀疑你的代码是否编译过!
问题是我从一个尚未存在的对象调用Child::foo()
(通过信号和插槽连接)。
相关文章:
- Qml 未收到基类成员变量的更新值
- 我如何实现从其基类获取变量的构造函数
- 变量(继承自基模板类)的偏移量,由具有相同名称的成员遮蔽
- 如何从派生类中的基类访问变量的值?
- 初始化基类和派生类中的类成员变量
- 决定对基类的变量指针进行函数调用
- 为什么我的基类指针变量不能访问派生类中的函数?
- 基类指针,访问派生的类成员变量
- 使用某些条件初始化派生类中的基类成员变量
- C++类函数继承使用从基类继承的另一个类的变量
- 我需要通过基类静态变量访问派生类成员
- 在派生类的构造函数的主体中初始化基类成员变量
- "Inherit"移动操作,而无需访问基类成员变量
- 在c++的派生类构造函数中访问基模板类中的变量
- 当基类具有两个或多个模板参数时,C++11 别名基模板类变量在模板派生类中不起作用
- 无法从c++基类访问变量
- 如何在派生类构造函数中初始化基类成员变量
- 抽象基类成员变量
- Shared_ptr对抽象基类(成员变量)是一个未声明的标识符
- 通过基类容器访问派生类唯一变量的最佳方式