这样定义拷贝构造函数会有什么问题?

we_sky2008 we_sky2008 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
#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;
}


请看程序和程序的注释。
程序本身并没什么意义,我只是想知道如果这样做会有什么后果,
谢谢大家!
...全文

相关推荐

评论 7
收藏 已收藏
分享
返回顶部
we_sky2008
C语言 70,039 成员 243,237 内容