首先我是一个初学者,但对编码非常热衷。
我有这个基类,从中继承了几个类。一个函数写在基类中,它需要被调用对象的大小。在函数编码时,大小是未知的,因为函数可能被不同派生类的对象调用。 到目前为止,我一直将大小作为参数传递,但应该有某种方式。
我尝试了 sizeof(*this),但 sizeof(*this) 返回了一个完全不同的值,它既不是基类的大小,也不是派生类的大小。我很困惑……有什么解释吗?
最佳答案
你可以编写一个返回对象大小的虚函数
struct Base
{
virtual size_t size() const { return sizeof( *this ); }
virtual ~Base(){}
};
struct Derived1 : Base
{
virtual size_t size() const { return sizeof( *this ); }
int x;
};
struct Derived2 : Base
{
virtual size_t size() const { return sizeof( *this ); }
int x;
int y;
};
Base *b = new Base;
Base *b1 = new Derived1;
Base *b2 = new Derived2;
std::cout << "b->size() = " << b->size() << std::endl;
std::cout << "b1->size() = " << b1->size() << std::endl;
std::cout << "b2->size() = " << b2->size() << std::endl;
关于C++ 继承 : How to get Size of called object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20419571/