【发布时间】:2015-10-09 19:07:53
【问题描述】:
我是 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 Invoked\n"; }
};
int main()
{
Student a;
Student b(a);
return 0;
}
根据我的理解,Student b(a); 所做的是复制 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。但它不编译。那么它是如何工作的呢?
【问题讨论】:
-
*this正在取消引用this指针以获取对象,它不会创建指向指针的指针。clone不是复制构造函数,它是一个普通的成员函数。在将基类返回到多态对象时,由于切片问题,它通过指针返回。clone的设计也很差,至少应该返回一个unique_ptr。 -
在网上搜索“c++ 工厂设计”和“c++ 双重委托”以获取更多示例。
-
@nwp 谢谢。
*this正在取消引用this指针以获取对象。这弄清楚我忽略了什么。使用上面的例子。SimulateCopyConstructor(*b);模拟情景。
标签: c++ pointers this copy-constructor