简体   繁体   中英

How to initialize static members in derived classes?

Well, apparently, I cannot. But that's my problem. Maybe it's a design issue and I'm getting the whole thing wrong.

I would like to have a class member initialized differently within each derived class. Imagine I have an object of type Device . This Device is just an interface used by the application code, because the actual devices are just one of two types, DeviceA or DeviceB . There are some features common to all devices, like, say, the name. That should be then a class member, shouldn't it? So I'd have:

class Device {
    static std::string sm_name;
}

But each family device has its own name. How could I initialize the name to a different value for each derived class? Is the design wrong? Should the name property not be a class member?

Should the name property not be a class member?

Each family device should, most likely, have it's own, private static member. You could use a virtual method to return the proper name on a device instance.

why not just have a virtual member function which returns the name, and implement it in the derived class to return the correct name?

eg

class A
{
public:
   virtual std::string name() = 0;
};

class B : public A
{
public:
virtual std::string name() { return "typeB"; }
};

class C : public A
{
public:
virtual std::string name() { return "typeC"; }
};

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