sizeof来自静态成员函数的C ++类

时间:2013-08-11 02:21:42

标签: c++ class inheritance sizeof member

我正在尝试编写一段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),因为这会破坏继承。 我知道这可以用宏来完成,但我更喜欢它作为类函数。

三江源

-

Kaelan

4 个答案:

答案 0 :(得分:1)

如果你坚持这样做,你应该使用模板,如下所示。

template <class SubClass>
static SubClass* allocate();

template <class SubClass>
SubClass *MyObject::allocate() {
    return (SubClass *)calloc(1, sizeof(SubClass));
    //or return new SubClass();  // this is better and is the C++ way
}

请注意,使用calloc可能会导致进一步的问题,首先是它不会调用构造函数。

此外,我认为您的意思是malloc,因为calloc似乎是针对数组的。

然后你会把它称为

MySubclass *instance = MyObject::allocate<MySubclass>();

您的代码不起作用,因为C ++没有“自我类型”的概念

答案 1 :(得分:0)

错误信息非常清楚。静态成员函数不属于任何特定对象,只能访问该类的静态数据成员。这就是为什么你不需要类实例来调用静态成员函数。

你可以尝试 -

MyObject *MyObject::allocate() {
    return new MyObject();
}

请记住删除资源。

答案 2 :(得分:0)

首先,你不应该使用calloc,而应该使用新的 其次,你可以使用sizeof(MyObject)
第三,即使这是可用的,sizeof(this)是指向对象的指针的大小,而不是对象本身

答案 3 :(得分:0)

看起来你要做的是覆盖operator new及其派生类的MyClass

class MyObject {
    int toastNumber;
    static void* operator new(std::size_t size) {
        void* ptr = ::operator new(size);
        std::cout << "Allocated " << size << " bytes at address "
                  << ptr << '\n';
        return ptr;
    }
};

编译器传递正确大小的块以进行分配,具体取决于您是分配实际的MyClass还是更大的派生类。预先警告它并不像你想象的那么有用。

你想用这个做什么?

相关问题