How to initialize static members in derived classe

2019-07-09 06:53发布

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?

2条回答
Luminary・发光体
2楼-- · 2019-07-09 07:41

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.

查看更多
做自己的国王
3楼-- · 2019-07-09 07:49

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

e.g.

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"; }
};
查看更多
登录 后发表回答