这样定义拷贝构造函数会有什么问题?
#include<iostream>
#include<string.h>
using namespace std;
class base
{
public:
base(char *str_b = "base")
{
this->str_b = new char[strlen(str_b) + 1];
strcpy(this->str_b, str_b);
}
base(const base& other)
{
this->str_b = new char[strlen(other.str_b) + 1];
strcpy(str_b, other.str_b);
}
virtual ~base()
{
delete str_b;
}
void display()
{
cout<<str_b<<endl;
}
private:
char *str_b;
};
class derived : public base
{
public:
derived(){}
derived(char* str_b, char *str_d) : base(str_b)
{
this->str_d = new char[strlen(str_d) + 1];
strcpy(this->str_d, str_d);
}
derived(derived& other)// : base(other)
{ //这样写的话会有什么问题?既不在初始化表里调用基类拷贝构造函数也不在函数体内直接赋值
base::base(other);//而是像这样来初始化基类部分 理论上应该会有内存泄露
this->str_d = new char[strlen(other.str_d) + 1];
strcpy(str_d, other.str_d);
}
virtual ~derived()
{
delete str_d;
}
void display()
{
base::display();
cout<<str_d<<endl;
}
private:
char *str_d;
};
int main()
{
derived d("hello", "world"), d1(d);
return 0;
}
请看程序和程序的注释。
程序本身并没什么意义,我只是想知道如果这样做会有什么后果,
谢谢大家!