在c ++中的一个定义规则 [英] One definition rule in c++

查看:196
本文介绍了在c ++中的一个定义规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据c ++标准:


无翻译单元应包含任何
变量的定义,类类型,枚举类型或模板。




  //  -  translation_unit.cpp-- // 
int a;

void foo()
{
int a; //第二次捍卫a。 ODR失败。你能解释一下ODR是如何工作的吗?





$ b

解决方案

这不会违反规则,因为你定义了两个不同的变量。它们具有相同的名称,但在不同的范围中声明,因此也是单独的实体。每个都有一个单独的定义。



函数范围中的声明被称为隐藏全局命名空间中的声明。在函数中,非限定名 a 是指局部变量,而限定名 :: a 是指全局。


According to the c++ standard:

No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.

//--translation_unit.cpp--//
int a;

void foo()
{
    int a; //Second defention of a. ODR fails.
}

Can you explain me how ODR does work actually?

解决方案

This doesn't break the rule because you define two different variables. They have the same name, but are declared in different scopes, and so are separate entities. Each has a single definition.

The declaration in the function's scope is said to hide the one in the global namespace. Within the function, the unqualified name a refers to the local variable, while the qualified name ::a refers to the global.

这篇关于在c ++中的一个定义规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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