#include <iostream>
using namespace std;
class Test {
int a;
public:
int getA() {
return a;
}
Test(): a(1){}
Test(int i): a(i){}
};
int main() {
Test t1(100);
cout << sizeof(t1) << " " << sizeof(1) << endl; // 4 4
return 0;
}
Run Code Online (Sandbox Code Playgroud)
似乎 C++ 中的类根本没有开销。t1 的大小为 4,就像一个整数。如果我向 Test 添加另一个 int 成员,它会将其大小增加到 8。
我会期望大于 4 的东西
课程没有开销是真的吗?
似乎 C++ 中的类根本没有开销。
只要一个类没有虚函数,那么,是的。你期望什么样的开销?无虚拟类只是变量的集合,具有与类型相关联的一组函数。
class Foo {
int a;
int bar() const { return a*a; }
};
Run Code Online (Sandbox Code Playgroud)
可以简单地替换为
struct Foo {
int a;
}
int Foo_bar(Foo const *that) {
return (that->a) * (that->a);
}
Run Code Online (Sandbox Code Playgroud)
如果您编译了这些片段中的每一个,您会看到,汇编代码看起来几乎相同。
然而,如果你添加一个单一的虚拟功能,游戏就会发生巨大的变化。