作为其他类成员的类:创建一个接受所有数据的构造函数
Class as members of other classes : Create a constructor that takes all data
我有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);
相关文章:
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 如何处理没有默认构造函数但在另一个构造函数中构造的对象?
- 我用字符串做了一个C++构造函数,但它不会打印出字符串
- 有一个构造函数,但有两个析构函数
- C++ 如何根据作为输入传递的参数调用一个构造函数或另一个构造函数?
- C 如何仅实现多个继承类的一个构造函数
- 错误:在“(”标记之前进行预期的构造函数、析构函数或类型转换.即使我有一个构造函数
- 让构造函数在其初始化列表中调用同一类的另一个构造函数是否有效
- 创建一个构造函数,即Capabe获取任何数量的参数
- 我如何在类上需要另一个构造函数的对象中声明一个对象
- 使用委托调用构造函数和在另一个构造函数体中调用的区别
- 为什么当我尝试编译时,我的 c++ 代码不断返回对我的一个构造函数的"未定义的引用"?
- C :另一个构造函数的构造函数的隐式调用
- 如何创建一个构造函数,该构造函数吸收char阵列
- 为什么有一个构造函数同时接受initializer_list和一个参数包
- 我有一个构造函数,但我需要将输出返回到 main.cpp.我无法使用获取字符串功能!!任何想法如何实现这一目标?
- 如何在一个构造函数中使用两个可变参数模板参数来绑定两个函数
- 从同一类的另一个构造函数调用构造函数
- 将类的实例传递给另一个构造函数,该构造函数将其对象添加到所传递实例所拥有的列表中