我正在尝试将一些Python类转换为c ++但是遇到了一些麻烦。我有一个Base类,它有一个类(静态)变量和一个返回它的方法。我还有一个派生类,它会覆盖类(静态)变量,如此,
在Python中:
class Base:
class_var = "Base"
@classmethod
def printClassVar(cls):
print cls.class_var
class Derived(Base):
class_var = "Derived"
d = Derived()
d.printClassVar()
打印出所需的派生类变量“Derived”。知道如何在c ++中获得相同的功能吗?我试过但最终得到了Base类的类变量。
在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();
}
答案 0 :(得分:3)
编写一个虚函数,返回对静态成员的引用:
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();
}
请注意printStaticVar
不应该是静态的。
您还可以在getter中将字符串static
设为本地:
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();
}
答案 1 :(得分:0)
另一种可能性可能是:
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) {}
};