模拟虚拟副本构造函数
Simulate a virtual copy constructor
我是c++的新手,只是通过看书来学习。所以这个问题可能有点愚蠢。这是我的程序:
#include <iostream>
using namespace std;
class Fish
{
public:
virtual Fish* Clone() = 0;
};
class Tuna : public Fish
{
public:
Tuna(const Tuna& SourceTuna)
{
cout << "Copy Constructor of Tuna invoked" << endl;
}
Tuna* Clone()
{
return new Tuna(*this);
}
};
我对有疑问
return new Tuna(*this);
首先,为什么复制构造函数返回Tuna的指针?通常,调用复制构造函数会直接返回一个复制的实例。例如:
class Student
{
public:
Student(){}
Student(const Student& Input) { cout << "Copy Ctor Invokedn"; }
};
int main()
{
Student a;
Student b(a);
return 0;
}
根据我的理解,Student b(a);
所做的是复制一个名为b
的实例。那么,为什么new Tuna(*this)
不返回实例而不是指针呢?
第二,为什么这是重点,即。论点中提供的*this
?根据我的理解,this
是一个指向当前对象的指针,这意味着*this
是指向当前对象指针的指针。我尝试使用int
来模拟这种情况。
// The input argument is the same as a copy constructor
int SimulateCopyConstructor(const int& Input){ return 0; }
void main()
{
int a = 10; // a simulate an object
int* b = &a; // b is a pointer of object a, which simulate "this"
int** c = &b; // c is a pointer to pointer of object a, which simulate of "*this"
SimulateCopyConstructor(a); // It can compile
SimulateCopyConstructor(b); // cannot compile
SimulateCopyConstructor(c); // cannot compile
}
我认为将(*this)
发送到复制构造函数与上面的情况c类似。但它不会编译。那么它是如何工作的呢?
Student b(a);
不返回Student
对象。它声明它,并指示编译器在堆栈上分配的新对象上调用复制构造函数。
new Student(a);
这确实返回了一个指向新Student
对象的指针,因为operator new
确实返回了。其中(a)
指示编译器在new
分配的对象上调用复制构造函数。
然而,如果你有一个功能可以做到这一点:
Student foo(){ return Student(a); }
这将在堆栈上创建一个新的Student
对象,调用复制构造函数,然后从函数返回结果对象。
相关文章:
- 如何从构造函数副本 T(const T&)调用对象 T?
- 当类型适当的构造函数可用时,为什么一个编译器尝试使用已删除的副本构造函数
- 复制构造函数生成旧数组的错误副本
- 复制构造函数和运算符"="他们没有打印列表 l 的副本
- 是否可以编写便于副本初始化的显式构造函数
- 该代码调用副本或移动构造函数
- 我应该声明我的异常的副本构造函数noexcept吗
- 复制构造函数不起作用,无法修改副本
- C++中的构造函数副本、列表、指针和模板
- 具有未定义参数的私有副本构造函数
- 构造函数初始化列表中的 C 结构副本C++
- 使用函数中的复制构造函数创建实例的副本,该函数获取作为基对象传递的实例
- 错误的数组初始化与赋值副本构造函数初始化
- 如何制作此构造函数的深层副本
- 为二进制搜索树副本构造函数编写辅助函数
- 在循环构造函数调用中创建的对象的副本
- 使用已删除的副本构造函数和初始值设定项列表重载调用类定义中的成员构造函数
- C++通过对构造函数的引用传递.成员将是一个完整的私人副本
- 如果引发的异常始终是异常对象的副本,为什么不调用此复制构造函数?
- 模拟虚拟副本构造函数