0

以下代码不违反一个定义规则,但它给出了意想不到的结果:

测试.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++ 标准会有所帮助)。

4

1 回答 1

3

您不能将函数定义为既inline和非inline.

如果具有外部链接的函数在一个翻译单元中声明为内联,则应在其出现的所有翻译单元中声明为内联;不需要诊断。

([dcl.fct.spec]/4)

于 2015-11-04T23:29:22.607 回答