这样定义拷贝构造函数会有什么问题?
#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;
}
请看程序和程序的注释。
程序本身并没什么意义,我只是想知道如果这样做会有什么后果,
谢谢大家!
#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;
}
请看程序和程序的注释。
程序本身并没什么意义,我只是想知道如果这样做会有什么后果,
谢谢大家!
...全文
相关推荐
C++拷贝构造函数详解[可运行源码]
本文详细介绍了C++中拷贝构造函数的定义、使用条件、浅拷贝与深拷贝的区别及其应用场景。拷贝构造函数是一种特殊的构造函数,用于基于同一类的其他对象进行构建及初始化。文章通过代码示例展示了拷贝构造函数的基本用法,并深入探讨了浅拷贝和深拷贝的差异,特别是在处理动态内存分配时的注意事项。此外,还解答了关于拷贝构造函数的多个常见问题,如为什么必须使用引用传递、拷贝构造函数的作用等,为C++开发者提供了全面的参考。
学习C++的一些基本问题
1. 面向对象的程序设计思想是什么? 答:把数据结构和对数据结构进行操作的方法封装形成一个个的对象。 2. 什么是类? 答:把一些具有共性的对象归类后形成一个集合,也就是所谓的类。
C++程序员面试题集
关于C++基础的文档,其中有大量关于C++面试过程中所有的题目。
C++与操作系统等面试题34
C++与操作系统等面试题34
c++学习笔记
c++学习笔记,本人开发过程中遇到的一些问题,现在和大家分享


