|
本帖最后由 sunguofu8 于 2021-3-12 09:38 编辑
老师们好!我在学习C++0基础入门的36课,做完成作业时遇到如下问题,麻烦您给指点一下,多谢您!按着课上讲的,由于多delete一次name的内存空间,所以会报错中断的,我采用拷贝构造函数时也一样。代码如下:
// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
//#include "Student.h"
using namespace std;
class CStest
{
public:
char* name;
int age;
CStest(){};
CStest(CStest& cst) //这就是拷贝构造函数,实现复制。
{
this->name = new char(strlen(cst.name) + 1);
strcpy(name, cst.name);
this->age = cst.age;
}
CStest(char* t_name,int t_age)
{
name = new char(strlen(t_name) + 1);
strcpy(name, t_name);
this->age = t_age;
}
~CStest() //这是析构函数,用于内存的释放delete.
{
if (name)
{
delete name;
}
}
protected:
private:
};
void test() //定义函数,创造对象,并赋值。
{
/*CStudent stu1 = {"sunguofu",13};*/
CStest test1 = { "sunguofu", 13 }, test2;
test2 = test1;
}
int _tmain(int argc, _TCHAR* argv[])
{
test(); //调用函数,当函数执行后就报销。
return 0;
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
以前帖子的方法也测试过,还是不行的。
CStest(CStest& cst)
{
int dst_name_len = 0;
if (cst.name)
{
dst_name_len = strlen(cst.name );
}
name = 0;
if (dst_name_len>0)
{
this->name = new char(dst_name_len+1);
memset(name, 0, dst_name_len);
strcpy(name, cst.name);
}
this->age = cst.age;
}
本帖最后由 tony666 于 2021-3-12 09:51 编辑
你这调的是operator= 不是拷贝构造函数 ,拷贝构造函数是 “构造函数”
- CStest test1 = { (char*)"sunguofu", 13 }, test2(test1);
复制代码
另外this->name = new char[strlen(cst.name) + 1];
new 数组用中括号
|
上一篇: 关于c++编写exe小程序下一篇: 关于shellcode调用崩溃的问题
|