简体   繁体   中英

Accessing protected static members of Superclass by Sub-classes in C++

I have a question. If I have a static member in the superclass, how do I allow all sub-classes of this superclass access and use the static member.

Eg

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

May I know what is wrong here? Thanks in advance!

EDIT:

The Container class is as follows

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

The error given is: "Use of undeclared identifier "database"

Define that static member out of the class declaration:

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.

Your way to make it protected is OK to make it accessible for derived classes.

Your code looks ok except missing definition of static Commands member database . You need to define database outside commands class

Container Commands::database;

§ 9.4.2 Static members

Static members obey the usual class member access rules (Clause 11) . When used in the declaration of a class member, the static specifier shall only be used in the member declarations that appear within the member-specification of the class definition.

As database is a protected member of base class Commands , derived class Add should be able to access it by :: operator or . operator from object.

Since static member is shared between all objects. Commands::database should be OK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM