带有参数列表的C ++构造函数

问题描述 投票:0回答:2

我熟悉C ++中的构造函数,想知道为什么我的C ++编译器找不到带有参数列表的构造函数。

#include <cstdio>
#include <string>

const int defaultAge = 0;
const std::string unknown = "unknown";

class Patient {

    public:
     int age;
     std::string dob;
     std::string name;

    public:
     Patient();                                                           // Default Constructor
     Patient(int &years, std::string &birthdate, std::string &aliase);    // Argument-List Constructor
     void print();
};

Patient::Patient() : age(defaultAge), dob(unknown), name(unknown) {
    puts("Patient information from default consturctor:");
}

Patient::Patient(int &years, std::string &birthdate, std::string &aliase) 
: age(years), dob(birthdate), name(aliase) {
    puts("Patient information from copy consturctor:");
}

void Patient::print() {
    printf(" Name - %d\n DOB  - %s\n Name - %s\n", age, dob.c_str(), name.c_str());
}

int main(void) {

    Patient p0;
    p0.print();

    Patient p1(40, "August 11, 1980", "John Doe");
    p1.print();

    return 0;
}

尝试编译代码时收到以下错误:

compilation error

我正在使用Apple clang版本11.0.0作为编译器

c++ constructor arguments pass-by-reference move-constructor
2个回答
2
投票

您将参数声明为对非常量的左值引用,该值不能绑定到40"August 11, 1980""John Doe"之类的右值。


0
投票

songyuanyao指出了您的代码存在的问题。一个好的选择是传递值,然后移动:

© www.soinside.com 2019 - 2024. All rights reserved.