我有2个课本和作者。图书的成员之一是作者类型。 在Class Books上,我希望有一个构造器,该构造器接受book和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和author的所有参数?
谢谢!
答案 0 :(得分:0)
在这种情况下,可以使用成员初始化器列表;这些是特殊的逗号分隔的表达式列表,在构造函数主体中的:
之后,以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);