gpt4 book ai didi

具有相同名称的 C++ 内联函数和外部函数给出意外结果

转载 作者:行者123 更新时间:2023-11-28 00:10:15 25 4
gpt4 key购买 nike

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

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

最佳答案

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

If a function with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required.

([dcl.fct.spec]/4)

关于具有相同名称的 C++ 内联函数和外部函数给出意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33533944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com