Skip to content

派生类的拷贝构造函数的规范实现应该是调用基类的拷贝构造函数来进行初始化派生类对象的基类部分 #34

@ltimaginea

Description

@ltimaginea

Issue1

class MyMap: pubic MyString

派生访问说明符拼写错了,应该是 public 而不是 pubic

Issue2

MyMap(const MyMap & mm): MyString(mm.buf_len, mm.characters)
{
//allocate memory for keyname
//and hard copy from mm to *this
}

  1. 派生类的构造函数、拷贝构造函数和拷贝赋值运算符通常应该是 public 而不需要是 private

  2. 派生类的拷贝构造函数的规范实现应该是调用基类的拷贝构造函数来进行初始化派生类对象的基类部分,课件这里,调用基类的普通构造函数是不合适的,并且程序也是无法通过编译的,因为基类MyString的数据成员是 private 的,所以派生类MyMap是无法直接访问基类的 buf_lencharacters 数据成员的。

派生类MyMap的拷贝构造函数的规范实现代码如下:

public:
	MyMap(const MyMap& mm) : MyString(mm), keyname( /* initialize derived class members */)
	{
		// Do the rest of the copy constructor here...
	}

派生类的拷贝控制成员的规范实现示例代码如下:

#include <iostream>
#include <string>
#include <utility>

class Base
{
	// ...
public:
	Base() = default;
	Base(const Base&) = default;
	Base(Base&&) = default;
	Base& operator=(const Base&) = default;
	Base& operator=(Base&&) = default;
	virtual ~Base() = default;
	// ...
};

class Derived : public Base
{
	// ...
public:
	Derived() = default;

	Derived(const Derived& rhs) : Base{ rhs }, derived_{ rhs.derived_ }
	{
		// Do the rest of the copy constructor here...
	}

	// If the move constructor doesn't throw an exception, it should be marked noexcept.
	Derived(Derived&& rhs) noexcept : Base{ std::move(rhs) }, derived_{ std::move(rhs.derived_) }
	{
		// Do the rest of the move constructor here...
	}

	Derived& operator=(const Derived& rhs)
	{
		// The copy assignment operator can gracefully handle self-assignment.
		if (this != &rhs)
		{
			Base::operator=(rhs);
			derived_ = rhs.derived_;
			// Do the rest of the copy assignment operator here...
		}
		return *this;
	}

	// If the move assignment operator doesn't throw an exception, it should be marked noexcept.
	Derived& operator=(Derived&& rhs) noexcept
	{
		// The move assignment operator can gracefully handle self-assignment.
		if (this != &rhs)
		{
			Base::operator=(std::move(rhs));
			derived_ = std::move(rhs.derived_);
			// Do the rest of the move assignment operator here...
		}
		return *this;
	}

	~Derived() override = default;
private:
	std::string derived_;
	// ...
};

int main()
{
	Derived d0, d1, d2;
	Derived d3{ d0 };
	Derived d4{ std::move(d0) };
	d1 = d2;
	d1 = std::move(d2);
	return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions