gpt4 book ai didi

c++ - 声明和带有定义的声明。为什么不允许这样做?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:56:09 24 4
gpt4 key购买 nike

我想知道,为什么不允许这样写:

struct foo {      
void bar(); // declaration
void bar(){std::cout << "moo" << std::endl;} // declaration + definition
};

该函数声明了两次(我认为这没问题)并定义了一次。但是,我的编译器提示:

decldef.cxx:7:10: error: 'void foo::bar()' cannot be overloaded

为什么不允许?

为什么我的编译器 (g++ 4.7.2) 将此解释为重载?

PS:我知道如何写“正确的方式”,但我只是想知道,为什么上面是错误的。

最佳答案

来自§9.3

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 (14.7) appearing outside of the class definition, a member function shall not be redeclared.

此外,在这种情况下,陈述还可能违反:

A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.2), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition.

因为第一个声明没有将函数声明为内联。第二个定义隐式地做。

然而,这一点似乎不太令人信服。

关于c++ - 声明和带有定义的声明。为什么不允许这样做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34989641/

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