gpt4 book ai didi

c++ - 为什么我们不能重载构造函数来为其添加默认参数

转载 作者:行者123 更新时间:2023-11-28 02:38:38 24 4
gpt4 key购买 nike

让我们考虑以下示例:

我.

#include <iostream>

struct X {
X(){ };
X(const X&, int i = 6);
};

X::X(const X& x, int i) { std::cout << "ctor" << std::endl; }

X x;

X z = x;

int main()
{

}

DEMO

二.

#include <iostream>

struct X {
X(){ };
X(const X&, int i);
};

X::X(const X& x, int i = 7) { std::cout << "ctor" << std::endl; } //error:
//addition of default argument on redeclaration makes this constructor a copy constructor

X x;

X z = x;

int main()
{

}

DEMO

#include <iostream>

void foo(int i);
void bar(int j = 7);

void foo(int i = 7){ }
void bar(int j){ }

int main()
{

}

DEMO

示例 I 和 II 格式正确。但是为什么我们不能像函数一样重载构造函数(例二)呢?标准如何防止它?

最佳答案

关键是,一个类是平凡的还是平凡可复制的等等,实际上应该根据类定义来决定,而不需要了解整个程序。 §8.3.6 [dcl.fct.default]/p6(引用 N4140):

Except for member functions of class templates, the default arguments in a member function definition that appears outside of the class definition are added to the set of default arguments provided by the member function declaration in the class definition; the program is ill-formed if a default constructor (12.1), copy or move constructor, or copy or move assignment operator (12.8) is so declared.

参见 CWG issue 1344 .

关于c++ - 为什么我们不能重载构造函数来为其添加默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26687852/

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