我有一个问题。如果我在父类(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/