为什么不能编译?
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/