非成员函数可以声明多次,而成员函数只能声明一次?

发布于 2024-12-06 06:48:30 字数 406 浏览 5 评论 0原文

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

但为什么 ?

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 
}

Non mumber function can be delcared multiple times while member function can only be declared once? Is this right ? My example seems saying yes.

But Why ?

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 
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猫九 2024-12-13 06:48:30

根据标准 (2003),§8.3.6/4 说,

对于非模板函数,默认
参数可以稍后添加
同一函数中的函数声明

范围。

标准本身的示例:

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

第二个声明添加了默认值!

另请参阅§8.3.6/6。

还有一个有趣的(并且有些相关)主题:

和§9.3/2,

除了出现在类定义之外的成员函数定义,以及出现在类定义之外的类模板和成员函数模板 (14.7) 的成员函数的显式特化之外,成员函数
不得重新声明。

希望有所帮助。

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.

无戏配角 2024-12-13 06:48:30

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

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 函数的重新声明,因此必须允许它们。

You get the same result with this simplified version:

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
} ;

Perhaps the reason is historical -- lots of C code used redeclaration of extern functions, so they had to be allowed.

甜`诱少女 2024-12-13 06:48:30

它的确定性是有效的——但我认为这是不好的做法。

It certainity works - but I think it is bad practice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文