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

标签 c++

为什么不能编译?

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/

相关文章:

c++ - CreateEnvironmentBlock 使服务崩溃

c++ - 二叉搜索树中序树展示

c++ - 澄清 `boost::bind`和 `this`的使用

c++ - 如何实现具有 2 个键的哈希表?

c++ - QPushButton c++ 的动态 QGridLayout

c++ - 这个c++代码有什么问题?

c++ - 访问冲突写入位置未处理的异常

c++ - 使用 std::string 在 DLL 中创建类。 C4251 警告

java - C++,使用它从自身调用构造函数

c++ - 预编译 header 和 ASLR 有什么问题?