【发布时间】:2015-11-04 23:18:34
【问题描述】:
以下代码不违反一个定义规则,但它给出了意想不到的结果:
Test.hpp
class Test
{
public:
int test();
};
Test1.cpp
#include "Test.hpp"
int Test::test()
{
return 1;
}
int test1() // expected to return 1
{
Test a = Test();
return a.test();
}
Test2.cpp
#include "Test.hpp"
inline int Test::test() // doesn't violate ODR
{
return 99;
}
int test2() // expected to return 99
{
Test a = Test();
return a.test();
}
main.cpp
#include <iostream>
int test1();
int test2();
int main()
{
std::cout << test1() << std::endl;
std::cout << test2() << std::endl;
}
我希望它打印“1 99”,但它总是打印“1 1”。
关于Test::test的两个定义,因为其中一个是内联定义,所以也不违反一个定义规则。
所以这个程序是有效的,但它没有打印出预期的结果......
这个程序有什么问题吗?还是我对 ODR 规则有误解? (参考 C++ 标准会很有帮助)。
【问题讨论】:
-
Regarding two definitions of Test::test, since one of them is an inline definition, it does not violate ODR你是从哪里得到这个想法的? -
好吧,我认为它不违反 ODR,因为在 C++ 规范的 ODR 部分中没有提到这个问题。 “如果具有外部链接的函数在一个翻译单元中声明为内联,则应在其出现的所有翻译单元中声明为内联;不需要诊断。”在函数说明符部分提到,它不处理 ODR。