今天我在这篇博客里记录我做练习遇到的一个BUG,困扰了我两个小时的BUG最后也还是被我解决了。
在这里我简单的举一个例子来列明BUG的所在问题。
需求:
定义一个Human类,里面有private成员:char *name; int age;
再用Human类定义对象h1 。
h1定义时赋初值:h1(“张三”, 30);
最后将其打印出来。
根据需求可以知道,需要自己定义一个重载构造函数
BUG就在自定义的重载构造函数中
下面请看代码:
代码:
Human.h
#pragma once
#include <string>
class Human {
public:
Human(const char *name=NULL, int age=0);
~Human();
std::string description() const;
private:
char *name;
int age;
};
Human.cpp
#include <sstream>
#include "Human.h"
// 自定义重载构造函数
Human::Human(const char *nane, int age) {
// 如果name为空的话,就赋值“无名字”
if (!name) {
name = "无名字";
}
// 从堆上分配内存给name
this->name = new char[strlen(name)+1];
strcpy_s(this->name, strlen(name)+1, name); // 深拷贝
this->age = age;
}
Human::~Human() {
// 如果name不为空指针,就释放它的内存
if (name) {
delete[] name;
}
}
std::string Human::description() const {
std::stringstream ret; // 定义特殊的字符串变量
ret << "姓名:" << name << "\t年龄:" << age;
return ret.str();
}
main
#include <iostream>
#include "Human.h"
using namespace std;
int main(void) {
Human h1("张三", 30);
cout << h1.description() << endl;
system("pause");
return 0;
}
问题就出在Human.cpp文件中,不知道大家看出来没有
运行截图:
纳尼,直接崩掉了,这是怎么回事呢,明明代码都没有问题,也没有报错啊,,,简直是不可思议啊!!!
指针居然罢工了,叛逆了,这是怎么回事啊???
于是呢,就开始加断点,一步一步的排查,最后可以确定,问题就出在 自定义的重载构造函数中。
但是左右看又看貌似没有问题,,这是怎么回事呢?
Human::Human(const char *nane, int age) {
// 如果name为空的话,就赋值“无名字”
if (!name) {
name = "无名字";
}
// 从堆上分配内存给name
this->name = new char[strlen(name)+1];
strcpy_s(this->name, strlen(name)+1, name); // 深拷贝
this->age = age;
}
其实,问题就出在第一个参数中:
我错把 name 写成了 nane;
是不是很难看的出来;
就是这一个小小的错误,编译器就认不出name是谁了,后续的代码就全都错了,编译器就直接崩掉了。
现在我们把他改回来试试:
#include <sstream>
#include "Human.h"
// ***************************************
// Human::Human(const char *nane, int age)
Human::Human(const char *name, int age) {
// 如果name为空的话,就赋值“无名字”
if (!name) {
name = "无名字";
}
// 从堆上分配内存给name
this->name = new char[strlen(name)+1];
strcpy_s(this->name, strlen(name)+1, name); // 深拷贝
this->age = age;
}
Human::~Human() {
if (name) {
delete[] name;
}
}
std::string Human::description() const {
std::stringstream ret;
ret << "姓名:" << name << "\t年龄:" << age;
return ret.str();
}
运行截图:
问题完美解决。
总结:
以后不管自己是在做练习好,或者是出去工作也好,一定不能马虎,粗心大意,不然造成的后果是不可忽视的。