0

我有个问题。如果我在超类中有一个静态成员,我如何允许这个超类的所有子类访问并使用该静态成员。

例如

/*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);
};

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

4

3 回答 3

3

static从类声明中定义该成员:

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

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

静态数据成员在其类定义中的声明不是定义……静态数据成员的定义应出现在包含该成员的类定义的命名空间范围内。

您的方法可以使其protected可用于派生类。

于 2013-10-09T08:42:45.087 回答
2

您的代码看起来不错,除了缺少静态命令成员数据库的定义。您需要定义database外部commands

Container Commands::database;

§ 9.4.2 静态成员

静态成员遵守通常的类成员访问规则(第 11 条)。当在类成员的声明中使用时,静态说明符只能用于出现在类定义的成员规范中的成员声明中。

作为database基类的受保护成员Commands,派生类Add应该能够通过::运算符或.来自对象的运算符访问它。

于 2013-10-09T08:52:41.917 回答
0

由于static成员在所有对象之间共享。Commands::database应该可以。

于 2013-10-09T09:25:41.470 回答