c++ - 在 C++ 中通过子类访问父类(super class)的 protected 静态成员

标签 c++ inheritance polymorphism subclass superclass

我有一个问题。如果我在父类(super class)中有一个静态成员,我如何允许这个父类(super class)的所有子类访问和使用静态成员。

例如

/*Superclass*/
class Commands {
   protected:
            static Container database;
};

/*Sub class*/
class Add: public Commands {
   public:
            void add_floating_entry(std::string task_description);  
};

/*This gives me an error. add_floating_task is a method of the Container Class*/
void Add::add_floating_entry(string task_description)
{
   database.add_floating_task(task_description);
}

我可以知道这里出了什么问题吗?提前致谢!

编辑:

Container类如下

class Container {
private:
   vector<Task_Info*> calendar[13][32];
   vector<Task_Info*> task_list;
public:
   void add_floating_task(std::string task_description);
};

给出的错误是:“使用未声明的标识符“数据库”

最佳答案

在类声明之外定义static成员:

class Commands {
protected:
   static Container database; // <-- It's just a declration
};

Container Commands::database; // <-- You should make a definition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The declaration of a static data member in its class definition is not a definition ... The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition.

您使其 protected 的方法可以使派生类可以访问它。

关于c++ - 在 C++ 中通过子类访问父类(super class)的 protected 静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19266935/

相关文章:

future 是 c# XNA 还是 c++ directX11?

c++ - 初始化 map 被报告为空的奇怪行为

swift - 从 CollectionViewCell 呈现 View 时,调用中缺少参数 'coder' 的参数

德尔福XE : Can I call virtual constructors with parameters from a classtype-constrained generic type without resigning to hacks?

java - 当子类对象被指定为父类(super class)对象时会发生什么

c++ - 纯虚函数在 XCode 中实现失败

c++ - 有没有办法动态更改比较运算符?

java - 将实例分配给上层类的实例

c++ - 我可以告诉我的类是从哪个模板实例类继承的吗?

c++ - 访问存储在 vector C++中的结构的多态成员