【发布时间】:2010-08-18 14:59:49
【问题描述】:
有人告诉我,这些类型在它们自己的唯一翻译单元中可见,违反了单一定义规则。有人可以解释一下吗?
//File1.cpp
#include "StdAfx.h"
static struct S { int Value() { return 1; } } s1;
int GetValue1() { return s1.Value(); }
//File2.cpp
#include "StdAfx.h"
static struct S { int Value() { return 2; } } s2;
int GetValue2() { return s2.Value(); }
// main.cpp
#include "stdafx.h"
extern int GetValue1();
extern int GetValue2();
int _tmain(int argc, _TCHAR* argv[])
{
if( GetValue1() != 1 ) throw "ODR violation";
if( GetValue2() != 2 ) throw "ODR violation";
return 0;
}
我知道如何解决问题。根据标题,我正在寻找为什么它违反了 ODR。它如何违反:“在任何翻译单元中,模板、类型、函数或对象只能有一个定义。”?或者它可能违反了规则的不同部分。
【问题讨论】:
-
您违反了规则的另一部分。我已经用详细信息更新了我的答案。
标签: c++