0

几行代码值一千字:

我有三个简单的文件:header.h、main.cpp、other.cpp

// header.h

  #pragma once

inline const int& GetConst()
{
    static int n = 0;
    return n;
}

const int& r = GetConst();

// main.cpp

  #include "header.h"

int main()
{
    return 0;
}

// other.cpp

  #include "header.h"

在编译最简单的项目时,VC++ 2010 报错如下:

ClCompile:
  other.cpp
  main.cpp
  Generating Code...
  other.obj : error LNK2005: "int const & const r" (?r@@3ABHB) already defined in main.obj
D:\Test\Debug\bug.exe : fatal error LNK1169: one or more multiply defined symbols found

Build FAILED.

Time Elapsed 00:00:00.29
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我确信这是 VC++ 2010 的错误,因为以下两个参考:

1,C++ 标准说:(在 n3126 的第 140 页)

“声明为 const 且未显式声明为 extern 的对象具有内部链接。”

2,MSDN 说:(在:http: //msdn.microsoft.com/en-us/library/357syhfh (VS.80).aspx )

“在 C 中,常量值默认为外部链接,因此它们只能出现在源文件中。在 C++ 中,常量值默认为内部链接,这允许它们出现在头文件中。

const 关键字也可以用在指针声明中。”

4

1 回答 1

10

您从 C++ 标准中引用的段落为 (C++03 7.1.1/6):

已声明const和未显式声明的对象extern具有内部链接。

您尚未声明对象。你已经声明了一个引用。引用不是对象。也就是说,3.5/3 说:

具有命名空间范围的名称如果是显式声明为 const 且既未显式声明extern也未先前声明具有外部链接的对象或引用的名称,则该名称具有内部链接

然而,8.3.2/1 说:

Cv 限定的引用格式不正确

因此,虽然 const 限定的引用具有内部链接,但不可能对引用进行 const 限定。

您的示例程序中的引用不是 const-qualified,它是对 const-qualified 的引用int

于 2010-11-15T15:11:34.670 回答