作为其他类成员的类:创建一个接受所有数据的构造函数

Class as members of other classes : Create a constructor that takes all data

本文关键字:一个 构造函数 数据 成员 其他 创建      更新时间:2023-10-16

我有2个类书籍和作者。书籍的成员之一是作者类型。在类书籍上,我希望有一个构造函数,它采用书籍和作者的所有参数:这是我的代码:

class author
{
private :
    string name;
    string email;
public :
    string get_name(){return name;}
    string get_email(){return email;}
    void set_name(string name){this->name=name;}
    void set_email(string email){this->email=email;}
    author(string name,string email)
    {
        this->name=name;
        this->email=email;
    }
}
class book
{
private :
    string title;
    int year;
    author auth;
public:
    string get_title(){return title;}
    int get_year(){return year;}
    void set_title(string title){this->title=title;}
    void set_year(float year){this->year=year;}
    book(string title, int year):author(string name,string email)
    {
       this->title=title;
       this->year=year;
       ???????
    }
}

我不知道如何更改 book 的构造函数,以便它为书籍和作者获取所有参数?

谢谢!

在这种情况下,可以使用成员初始值设定项列表; 这些是以逗号分隔的特殊表达式列表,在构造函数主体中的:之后给出,形式为 member_variable(value)member_variable(values, to, pass, to, constructor) 。使用此构造,您的代码将类似于以下内容:

class Author {
    string _name;
    string _email;
public:
    Author(string name, string email)
        : _name(name)
        , _email(email)
    {/* nothing to do now */}
};
class Book {
    string _title;
    int _year;
    Author _author;
public:
    Book(string title, int year, Author author)
        : _author(author)
        , _title(title)
        , _year(year)
    {/* nothing to do now */}
    Book(string title, int year, string author_name, string author_email)
        : _author(author_name, author_email)
        , _title(title)
        , _year(year)
    {/* nothing to do now */}
};

但是,在以下情况下,这是一个有问题的解决方案:

Author bookish_writer("Bookish Writer", "bookishwriter@example.com");
Book a_book("A Book", 2019, bookish_writer);
// But what if I want to change bookish_writer's e-mail?
bookish_writer.set_email("the.real.bookish.writer@example.com");
// This will print bookishwriter@example.com
cout << a_book.get_author().get_email();

使用上面的代码,Author 对象将按值传递给构造函数,或在 Book 对象中创建。

一种解决方案是使用指针:

class Book {
    Author * _author;
    string _title;
    int _year;
public:
    Book(string title, int year, Author * author)
        : _author(author)
        , _year(year)
        , _title(title)
    {}
}

在这种情况下,您将使用:

Author bookish_writer("Bookish Writer", "bookishwriter@example.com");
Book a_book("A Book", 2019, &bookish_writer);
相关文章: