以下代码不违反一个定义规则,但它给出了意想不到的结果:
测试.hpp
class Test
{
public:
int test();
};
测试1.cpp
#include "Test.hpp"
int Test::test()
{
return 1;
}
int test1() // expected to return 1
{
Test a = Test();
return a.test();
}
测试2.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();
}
主文件
#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++ 标准会有所帮助)。