【发布时间】:2016-06-19 09:20:50
【问题描述】:
我有这段代码:
struct Type{
const char* name;
// other stuff
};
template <class T>
class Base{
public:
// some other functions
static const Type *Get_Type(){
/* Get the STATIC type of the class and make a new Type object */
virtual const Type *My_Type();
};
编辑:
我想实现两个成员函数,Get_Type() 和 My_Type()。
从 Base
我无权访问任何派生类,也无法更改 Get_Type() 和 My_Type() 的声明,但其他一切都是允许的。
Get_Type() - 应该实现返回调用它的类的类型。
My_Type - 应该实现返回调用对象的动态类类型。
例如:
class Derived1: public Base<Derived1> {
public:
Derived1() {}
};
class Derived2 : public Derived1 , public Base<Derived2> {
public:
Derived2() {}
};
int main() {
Derived1* b= new Derived2();
Derived2::Get_Type(); // should return a struct Type with name=Derived2
b->My_Type(); // should return a struct Type with name=Derived2
return 0;
}
我的问题是:
1) 我如何知道调用类的类型,在静态函数 Get_Type 的主体内?
2) 如何在 My_Type() 的主体中获取对象 (this) 的动态类型?
【问题讨论】:
-
你不能用静态函数做到这一点。
-
有办法解决吗?我可以更改 Base 但不能更改任何派生类
-
你可以使用基类中的普通成员函数和
typeid(this)来捕捉实际的类名。 -
你的意思是非静态成员函数?我以为我不能从静态调用非静态
-
为什么需要静态函数?我不明白你的意思。
标签: c++ oop inheritance static-members