C++ sizeof运算符是否更喜欢对象而不是类型? #包括 INTC; C类{ 私人: int i[2]; 公众: 静态int f(){ 返回大小f(C); } }; int f() { return sizeof(C);//为什么C不能是类类型C。 } int main() { std::cout

C++ sizeof运算符是否更喜欢对象而不是类型? #包括 INTC; C类{ 私人: int i[2]; 公众: 静态int f(){ 返回大小f(C); } }; int f() { return sizeof(C);//为什么C不能是类类型C。 } int main() { std::cout,c++,sizeof,C++,Sizeof,关于您的问题,sizeof没有任何特殊的解析或评估规则 考虑以下几点: #include <iostream> int C; class C { private: int i[2]; public: static int f() { return sizeof(C); } }; int f() { return sizeof(C); // why the C can't be the class t

关于您的问题,
sizeof
没有任何特殊的解析或评估规则

考虑以下几点:

#include <iostream> 

int C; 

class C { 
  private: 
    int i[2]; 
  public: 
    static int f() { 
        return sizeof(C); 
    } 
}; 

int f() 
{ 
    return sizeof(C); // why the C can't be the class type C.
} 

int main() 
{ 
   std::cout << "C::f() = " <<C::f() << "," 
             << " ::f() = " <<::f() << std::endl; 
} 

尝试编译这段代码会给你答案

#include <iostream>
#include <typeinfo>

int C; 

class C { 
public:
    int i[2]; 
}; 

int main() 
{ 
   // prints something that corresponds to "class C"
   // (or even "class C" itself):
   std::cout << typeid(class C).name() << "\n";

   // prints sizeof(int):
   std::cout << sizeof(C) << "\n";

   // prints sizeof(int) * 2:
   std::cout << sizeof(class C) << "\n";
} 
编译器:

prog.cpp:22:4: error: must use 'class' tag to refer to type 'C' in this scope
   C a;
   ^
   class 
prog.cpp:3:5: note: class 'C' is hidden by a non-type declaration of 'C' here
int C; 
    ^
1 error generated.
要获得正确的输出,请执行以下操作:

clang version 3.7.0 (tags/RELEASE_370/final 246979)
Target: x86_64-unknown-linux-gnu
Thread model: posix

sizeof
不是这个问题的关键。它恰好可以用于类型名或变量名。这些规则也适用于标识符的其他用途

§9.1[类别名称](c++标准草案n3797):

  • …snip…如果在一个范围内声明了一个类名,其中还声明了一个同名的变量、函数或枚举数,那么当两个声明都在该范围内时,只能使用详细的类型说明符引用该类
  • 在全局范围中有一个名为
    C
    的类和一个名为相同的变量。因此,只能使用详细的类型说明符(
    class C
    )引用该类

    然而,在
    C
    的定义中,该段的第一部分是相关的:

    §9.1[类别名称]:

  • 类声明将类名引入声明它的作用域,并在封闭的作用域中隐藏该名称的任何类、变量、函数或其他声明…snip
  • §9[类别]:

  • …snip…类名也插入到类本身的作用域中;这称为注入的类名…snip

  • 因此,在
    类C
    的作用域内,注入的类名对外部作用域隐藏了
    int C
    声明。因此,您可以引用
    C
    ,而无需详细的类型说明符。要引用全局
    int C
    ,您可以使用
    ::C
    对对象调用
    sizeof
    。类类型
    C
    不是一个对象,它是一个类的实现。如果您希望全局
    f()
    函数调用类类型
    C
    的对象,则需要初始化它的一个实例,即
    C;
    @RNar“
    sizeof
    在对象上被调用”不是。请参见:“[sizeof]查询对象或类型的大小。”因此,对象名称隐藏用户定义的类型名称(类、联合、枚举)?函数名呢?对象名是否也隐藏函数?函数名是否也隐藏用户定义的类型名?您使用的是哪种编译器?在启用警告的g++4.8.4下,它不会生成任何错误。它是在ideone上编译的,它没有说它使用了哪种编译器,但我猜是clang。我将在se中澄清cGreat答案!我还发现了一本非常有用的书。这个答案解释了为什么需要这些规则来向后兼容C。很好的发现。
    prog.cpp:22:4: error: must use 'class' tag to refer to type 'C' in this scope
       C a;
       ^
       class 
    prog.cpp:3:5: note: class 'C' is hidden by a non-type declaration of 'C' here
    int C; 
        ^
    1 error generated.
    
    clang version 3.7.0 (tags/RELEASE_370/final 246979)
    Target: x86_64-unknown-linux-gnu
    Thread model: posix
    
    int f() { 
        return sizeof(class C);
    }