【发布时间】:2019-07-08 19:20:17
【问题描述】:
我对复制构造函数和赋值运算符有一些疑问。我知道当我定义一个构造函数时,编译器不会合成默认构造函数。我怀疑是否可以只定义复制构造函数。我会说不,因为如果我定义了复制构造函数,则默认构造函数不会被合成,所以我无法初始化对象,因为我需要该类的对象,而我没有。我不知道这是否正确。我的第二个疑问是关于包含指针的类的类似值的实现。到目前为止,我看到的每个代码都在复制和赋值运算符中使用了 new 运算符。例如:
#include <string>
#include <vector>
#include "book.hh"
class Student
{
std::string name;
unsigned int id;
unsigned int age;
char gender;
std::vector<Book> * books;
/*Copy-constructor*/
Student (const Student & other)
{
name = other.name;
id = other.id;
age = other.age;
gender = other.gender;
books = new std::vector<Book> (*other.books);
}
/*Assignment operator*/
Student & operator = (const Student & other)
{
if (this != &other)
{
name = other.name;
id = other.id;
age = other.age;
gender = other.gender;
delete books;
books = new std::vector<book> (*other.books);
}
return *this;
}
}
文档说应该实现一个构造函数。构造函数呢?在这种情况下,如何在没有构造函数(不是复制构造函数)的情况下实例化一个类? Morover,我不明白为什么它在复制构造函数和赋值运算符中使用 new 。例如,我会在赋值运算符正文中执行 *books = *(other.books);这也是正确的吗?
【问题讨论】:
-
books需要一个内存插槽才能使*books = *(other.books);工作。因此,您需要为向量分配内存。当然使用动态分配的向量是有问题的,但我不确定你的问题在这里 -
...但既然你有一个
vector来持有Books -new似乎是个坏主意。 -
为什么是向量指针?
-
执行:
std::vector<Book> books;并在复制 ctor 和复制赋值运算符中:books = other.books; -
把
std::vector<Book> * books;改成std::vector<Book> books;,你就不需要定义任何特殊的成员函数了。
标签: c++ copy-constructor assignment-operator