构造函数中的默认参数会导致编译时错误

Default parameters in constructor gives compile time errors

我了解到我们可以为构造函数提供默认参数,以便它在代码中未明确提供的情况下初始化值,但是当我尝试创建我的 class 的对象时,它不会工作。如果没有提供,它不会采用这些默认值,它会给我一个错误,上面写着: error: no matching function for call to ‘Person::Person(const char [6], int)

Person::Person( string aName = "ANY", int age = 18 ) {
cout << "Constructor called!" << endl;
this->name = aName;
this->age = age;
}

现在当我在主程序中调用它时:

Person p( "Steve" );

它给了我提到的错误并且 age 默认情况下没有初始化为 18。

我正在为 C/C++ IDE

使用 eclipse

参数的默认值应该进入声明,而不是定义:

class C {
    C(int a = 0);
}

C::C(int a)    // not C::C(int a = 0)
{ ... }

正如 Evg 已经提到的:

default values for parameters should go into the declaration, not the definition

此外,我想指出的是,通常首选在构造函数中使用 'initializer list'(不要与 std::initializer_list 混淆),它看起来像这样:

#include <string>
#include <iostream>
class Person
{
public:
    Person(std::string aName = "ANY", int age = 18) : name(aName), age(age)
    {
        std::cout << "Constructor called!" << std::endl;
    }

    std::string name;
    int age;
};

int main()
{
    Person p1("Test123");
    std::cout << p1.name << ' ' << p1.age << std::endl;
    Person p2("Test456", 21);
    std::cout << p2.name << ' ' << p2.age << std::endl;

    return 0;
}

这样你的变量就被初始化一次,而且更干净。参见 https://en.cppreference.com/w/cpp/language/initializer_list。在您的示例中,nameage 将被默认初始化(甚至在执行构造函数主体之前)并分配给,此时您也可以立即使用正确的值对其进行初始化。