具有函数的类的c ++ sizeof()

2022-01-17 00:00:00 compiler-construction c++ sizeof

我有一个 C++ 问题.我写了以下课程:

I have a C++ question. I wrote the following class:

class c
{
    int f(int x, int y){ return x; }
};

c 类的 sizeof() 返回1".我真的不明白为什么它会返回 1.

the sizeof() of class c returns "1". I I really don't understand why it returns 1.

为了更好地理解发生了什么,我添加了另一个函数:

Trying to understand better what is going on, I added another function:

class c
{
     int f(int x, int y){ return x; }
     int g(int x, int y){ return x; }
};

现在下面真的让我很困惑!sizeof(c) 仍然是 1 (!?!?!?!).所以我猜函数不会改变类的大小,但是为什么呢???为什么尺寸是 1 ?它是特定于编译器的吗?

Now the following really got me confused! sizeof(c) is still 1 (!?!?!?!). So I guess that functions doesn't change the size of the class, but why??? and why does the size is 1 ? And is it compiler specific ?

谢谢!:-)

推荐答案

该类不包含数据成员,因此为空.标准要求每个班级至少有大小 1,所以这就是你得到的.(成员函数实际上并不在类内部",它们实际上只是具有隐藏参数、命名空间和访问控制的自由函数.)

The class contains no data members, so it's empty. The standard demands that every class have at least size 1, so that's what you get. (Member functions aren't physically "inside" a class, they're really just free functions with a hidden argument and a namespace and access control.)

相关文章