为什么在C和C ++中相同标识符的大小不同? [英] Why does the size of the same identifier differ in C and C++?

查看:87
本文介绍了为什么在C和C ++中相同标识符的大小不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
int T;
int main()
{
    struct T { double x; };  
    printf("%zu", sizeof(T));
    return 0;
}

如果我在C中运行此代码,则结果为4,而在C ++中为8.

If I run this code in C, the result is 4, while in C++ it is 8.

有人可以解释为什么有区别吗?

Can someone explain why the difference?

推荐答案

简短的回答:实际上,因为它们不是相同的标识符.

Short answer: Because they aren't the same identifier, in fact.

在C中,结构名称和变量名称属于 不同的命名空间 ,因此在C中,

In C, structure names and variable names fall into different namespaces, so in C,

sizeof(T) == sizeof(int) // global variable T
sizeof(struct T) == sizeof(struct T) // not the same namespace

但是,在C ++中,结构/类名称作为变量进入同一命名空间. 最近的"(最本地的)名称名称查找,所以现在

In C++, however, structure/class names goes into the same namespace as variables. The "nearest" (most local) name is the result of name lookup, so now

sizeof(T) == sizeof(struct T) // structure T
sizeof(::T) == sizeof(int) // Note the scope resolution operator

因此,结果分别为4和8.

And therefore the result is 4 and 8, respectively.

在C ++中,使用sizeof(::T)可以获得4. 双冒号"作用域解析运算符强制编译器在外部命名空间中使用T作为名称,因此::T是所需的int类型的变量.

In C++, you can get 4 with sizeof(::T). The "double-colon" scope resolution operator forces the compiler to take T as the name in external namespace, so ::T is the variable of type int that you want.

在C语言中,(结构/联合/枚举)和(变量/函数/类型定义)具有独立的命名空间,因此您可以编写此文件而不必担心名称冲突.

In C, (structures/unions/enums) and (variables/functions/typedefs) have separate namespaces, so you can write this without worrying about names conflicting.

struct T T;

请注意括号,即结构,联合和枚举共享一个名称空间,而其他三个共享另一个名称空间.

note the parentheses, that structs, unions and enums share one namespace while the other three share another.

如果尝试使用C ++进行此操作,则会立即遇到问题.

If you try to do this in C++, you'll immediately run into problems.

我喜欢 hacck的评论.他指出,根本原因是尽管C和C ++相似,但它们是不同的语言.

I like hacck's comment. He got the point that the fundamental reason is that C and C++ are different languages, despite their similarity.

这篇关于为什么在C和C ++中相同标识符的大小不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆