如何修复 "cannot convert"?

How to fix "cannot convert"?

我遇到了编译错误 "cannot convert.."、`"no instance of constructor.."。我无法理解我做错了什么。我试图改变对象的初始化方式,但没有帮助。想更好地理解这一点。

    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    struct Specialization {
        string data;
        explicit Specialization(string& new_value) {
            data = new_value;
        }
    };
    struct Course {
        string data;
        explicit Course(string& new_value) {
            data = new_value;
        }
    };
    struct Week {
        string data;
        explicit Week(string& new_value) {
            data = new_value;
        }
    };
    struct LectureTitle {
        string specialization;
        string course;
        string week;
        LectureTitle(Specialization& new_value1, Course& new_value2, Week new_value3) {
            specialization = new_value1.data;
            course = new_value2.data;
            week = new_value3.data;
        }
    };

    int main() {
        LectureTitle title (
            Specialization("C++"),
            Course("White belt"),
            Week("4th")
        );

    }
LectureTitle title (
        Specialization("C++"),
        Course("White belt"),
        Week("4th")
    );

在这里您尝试创建一个 LectureTitle 的实例,其临时值 (rvalues) 为 SpecializationCourseWeek。它们是临时的,因为它们不是命名变量,即在这段代码之前没有定义为变量。

但是,您的所有构造函数都采用命名变量引用 (lvalues)。这就是你得到编译器错误的原因。要更正这些错误,您可以让构造函数接受 const 值引用,如下所示:

explicit Specialization(const std::string& new_value) {
    data = new_value;
}

explicit Course(const std::string& new_value) {
    data = new_value;
}

explicit Week(const std::string& new_value) {
    data = new_value;
}

LectureTitle(const Specialization& new_value1, const Course& new_value2, const Week new_value3) {
    specialization = new_value1.data;
    course = new_value2.data;
    week = new_value3.data;
}

常量左值引用可以绑定到右值——即延长临时对象的生命周期;这些临时变量可用于初始化构造函数中的成员变量。