簡體   English   中英

類作為其他類的成員:創建一個接受所有數據的構造函數

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

我有 2 個類書籍和作者。 Books 的成員之一是 Author 類型。 在課堂書籍上,我想要一個構造函數,它接受書籍和作者的所有參數:這是我的代碼:

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 的構造函數,以便它采用 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM