2

非成员函数可以多次声明,而成员函数只能声明一次?这是正确的吗 ?我的例子似乎是肯定的。

但为什么 ?

class Base{
public:
    int foo(int i);
    //int foo(int i=10); //error C2535: 'void Base::foo(int)' : member function already defined or declared
};

//but it seems ok to declare it multiple times
int foo(int i);
int foo(int i=10);

int foo(int i)
{
    return i;
}

int main (void)
{
    int i = foo();//i is 10 
}
4

3 回答 3

6

From the Standard (2003), §8.3.6/4 says,

For non-template functions, default arguments can be added in later declarations of a function in the same scope.

Example from the Standard itself:

void f(int, int);
void f(int, int = 7);

The second declaration adds default value!

Also see §8.3.6/6.

And an interesting (and somewhat related) topic:

And §9.3/2,

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.

Hope that helps.

于 2011-09-22T17:14:02.940 回答
1

使用此简化版本您会得到相同的结果:

int foo() ;
int foo() ; // OK -- extern functions may be declared more than once
class C {
  int foo() ;
  int foo() ; // Error -- member function may not be declared more than once
} ;

也许原因是历史原因——大量C代码使用了extern函数的重新声明,所以它们必须被允许。

于 2011-09-22T17:36:49.017 回答
0

它确实有效 - 但我认为这是不好的做法。

于 2011-09-22T17:17:55.973 回答