gpt4 book ai didi

c++ - 声明,然后定义一个类方法——为什么会出错?

转载 作者:太空宇宙 更新时间:2023-11-04 15:13:20 25 4
gpt4 key购买 nike

为什么不能编译?

class Test
{
void foo();
void foo()
{ }
};

但是这些将编译:

void bar();
void bar()
{ }

// In same header/file
class Test
{
void foo();
};
void Test::foo()
{ }

编译器会说给定的方法 cannot be overloaded . Test::foo 方法没有被重载 - 它是具有完全相同签名的相同函数。

最佳答案

这是 C++ 标准明确禁止的。就在 [class.mfct/1]

A member function may be defined in its class definition, in which case it is an inline member function, or it may be defined outside of its class definition if it has already been declared but not defined in its class definition. A member function definition that appears outside of the class definition shall appear in a namespace scope enclosing the class definition. Except for member function definitions that appear outside of a class definition, and except for explicit specializations of member functions of class templates and member function templates ([temp.spec]) appearing outside of the class definition, a member function shall not be redeclared.

关于c++ - 声明,然后定义一个类方法——为什么会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44692931/

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