据我所知在下列情况下调用复制构造函数:
1当实例化一个对象并使用来自另一个对象的值初始化它时
2按值传递对象时。
3通过值从函数返回对象时。
我决定把它用于测试,并且我让这个小程序测试了这个(每次调用构造函数时都会收到消息,它似乎适用于前两种情况,但不适用于第三种情况,我想知道我的错误。想法是欢迎。复制构造函数未调用?
#include <iostream>
using namespace std;
class Circle{
private:
double* data;
public:
Circle();
Circle(double* set);
Circle(const Circle& tt1);
~Circle();
Circle& operator=(const Circle& tt1);
};
Circle :: Circle()
{
cout << "Default constructor called" << endl;
data = NULL;
}
Circle :: Circle(double* set)
{
cout << "Set up constructor called" << endl;
data = new double[3];
copy(set, set+3, data);
}
Circle :: Circle(const Circle& tt1)
{
cout << "Copy constructor called" << endl;
data = new double[3];
copy(tt1.data, tt1.data+3, this->data);
}
Circle :: ~Circle()
{
cout << "Destructor called!" << endl;
delete[] data;
}
Circle& Circle :: operator=(const Circle& tt1)
{
cout << "Overloaded = called" << endl;
if(this != &tt1)
{
delete[] this->data;
this->data = new double[3];
copy(tt1.data, tt1.data+3, this->data);
}
return *this;
}
void test2(Circle a)
{
}
Circle test3()
{
double arr [] = { 3, 5, 8, 2};
Circle asd(arr);
cout<< "end of test 3 function" << endl;
return asd;
}
int main()
{
cout <<"-------------Test for initialization" << endl;
double arr [] = { 16, 2, 7};
Circle z(arr);
Circle y = z;
cout << "-------------Test for pass by value" << endl;
test2(z);
cout <<"------------- Test for return value-------"<<endl;
Circle work = test3();
cout<< "-----------Relese allocated data" << endl;
return 0;
}
你没有错。它只是优化了。 – jrok
哇。我花了几个小时思考这个问题。至少我现在不会忘记它! – Bloodcount
@Bloodcount重要的是你学会了它,不会忘记它。如果你问我,这些花费几个小时。 –