加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 重新声明时替换函数默认参数

发布时间:2020-12-16 07:10:39 所属栏目:百科 来源:网络整理
导读:参见英文答案 Default argument in the middle of parameter list?????????????????????????????????????2个 为什么以下代码格式正确: void foo(int i,int j = 56);void foo(int i = 42,int j);int main(){ } DEMO 但以下 void foo(int i = 42,int j);void
参见英文答案 > Default argument in the middle of parameter list?????????????????????????????????????2个
为什么以下代码格式正确:

void foo(int i,int j = 56);
void foo(int i = 42,int j);

int main(){  }

DEMO

但以下

void foo(int i = 42,int j);
void foo(int i,int j = 56);

int main(){  }

DEMO

是不正确的.我试着查看N4296 :: 8.3.6 [dcl.fct.default],我发现的是以下示例:

class C 
{
    void f(int i = 3);
    void g(int i,int j = 99);
};
void C::f(int i = 3) { } //error
void C::g(int i = 88,int j) { // C::g can be called with no argument
}

但是clang似乎并不那样.

struct A
{
    void foo(int i = 42,int j);
};

void A::foo(int i,int j = 56){ }; //error

int main(){  }

DEMO

那么,这是一个实施问题吗?在形式上,所有这个例子应该是可以接受的,如果它们?

解决方法

[dcl.fct.default]

  1. […]default arguments can be added in later declarations of a function in the same scope.
void foo(int i,int j);

这很好,因为第二个声明是为第一个参数添加一个默认参数,该参数之前没有.

[…]In a given function declaration,each parameter subsequent to a parameter with a default argument shall have a default argument supplied in this or a previous declaration[…]

第二个声明中的第二个参数已经有一个默认参数,尝试提供另一个参数将是一个错误.

void foo(int i = 42,int j); // error
void foo(int i,int j = 56);

这是一个错误,因为第一个声明为第一个参数提供了默认参数,但没有为第二个参数提供默认参数,并且与第一个示例不同,之前没有声明.

struct A
{
    void foo(int i = 42,int j); // the error should be here
};

void A::foo(int i,int j = 56){ }; // not here

这与上面完全相同的原因是不正确的,j在初始声明中没有默认参数,示例中的下一行是无关紧要的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读