【发布时间】:2013-08-11 02:21:41
【问题描述】:
我正在尝试编写一段 C++ 代码,从静态类成员中分配一个类的实例,同时让它知道任何继承的子类的大小
.h 文件
class MyObject {
int toastNumber;
static MyObject *allocate();
}
class MySubclass : public MyObject {
int NSABackdoor;
int someOldFunction();
}
.cpp 文件
#include ".h file"
MyObject *MyObject::allocate() {
return (MyObject *)calloc(1, sizeof(this)); // error here
}
int MySubclass::someOldFunction() {
return 6;
}
main.cpp 文件
#include other files
int main() {
MySubclass *instance = MySubclass::allocate();
return 0;
}
在尝试编译代码时,g++ 会吐出类似的错误
MyObject.cpp: In static member function ‘static MyObject* MyObject::allocate()’:
MyObject.cpp:5:47: error: ‘this’ is unavailable for static member functions
可以像这样从成员函数中分配实例吗? 我不能只使用 sizeof(MyObject) 因为那会破坏继承。 我知道这可以通过宏来完成,但我更喜欢它作为类函数。
谢谢
--
凯兰
【问题讨论】:
-
不要在 C++ 中使用 calloc(使用 new),并且不能在静态成员函数中使用
this,这是没有意义的。sizeof(MyObject)会起作用。 -
@Borgleader 他试图从
this获取类名而不是对象。但是是的,因为 C++ 不支持这个,所以不起作用。 -
您是否偶然将
static与virtual混淆了?
标签: c++ class inheritance sizeof member