简体   繁体   English

C ++继承成员函数使用静态变量

[英]C++ Inheritance member functions using static variables

I am trying to convert some Python classes into c++ but am having some trouble. 我试图将一些Python类转换为c ++但是遇到了一些麻烦。 I have a Base class which has a class (static) variable and a method which returns it. 我有一个Base类,它有一个类(静态)变量和一个返回它的方法。 I also have a derived class which overrides the class (static) variable like so, 我也有一个派生类,它会覆盖类(静态)变量,如此,

In Python: 在Python中:

class Base:
   class_var = "Base"
   @classmethod
   def printClassVar(cls):
      print cls.class_var

class Derived(Base):
   class_var = "Derived"

d = Derived()
d.printClassVar()

which prints out the desired derived class variable, "Derived". 它打印出所需的派生类变量“Derived”。 Any idea how I can get the same functionality in c++? 知道如何在c ++中获得相同的功能吗? I have tried but end up getting the class variable of the Base class. 我已经尝试但最终获得Base类的类变量。

In c++ 在c ++中

class Base
{
public:
    static void printStaticVar(){cout << s_var << endl;}
    static string s_var;
};
string Base::s_var = "Base";

class Derived : public Base
{
public:
    static string s_var;
};
string Derived::s_var = "Derived";

void main()
{
    Derived d;
    d.printStaticVar();
}

Write a virtual function which returns a reference to the static member: 编写一个虚函数,返回对静态成员的引用:

class Base
{
public:
    void printStaticVar() {cout << get_string() << endl;}
    static string s_var;
    virtual string const& get_string() { return Base::s_var; }
};
string Base::s_var = "Base";

class Derived : public Base
{
public:
    static string s_var;
    virtual string const& get_string() { return Derived::s_var; }
};
string Derived::s_var = "Derived";

void main()
{
    Derived d;
    d.printStaticVar();
}

Note that printStaticVar shouldn't be static. 请注意, printStaticVar不应该是静态的。


You could also make the string static local inside the getter: 您还可以在getter中使字符串static local:

class Base
{
public:
    void printStaticVar() {cout << get_string() << endl;}
    virtual string const& get_string() { 
        static string str = "Base";
        return str;
    }
};

class Derived : public Base
{
public:
    virtual string const& get_string() { 
        static string str = "Derived";
        return str;
    }
};

void main()
{
    Derived d;
    d.printStaticVar();
}

Another possibility might be: 另一种可能性是:

class Base
{
  const std::string var;
public:
  Base(std::string s="Base") : var(s) {}
  void printVar() { std::cout << var << std::endl }
};
class Derived : public Base
{
public:
  Derived(std::string s="Derived") : Base(s) {}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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