这张图中使用了new来创建空间,能够正确的输出Apple
这张图没有任何输出结果
#include <iostream>
#include <string>
using namespace std;
class person {
char* name_;//这个指针只是个指针变量,占用的空间大小也就4个字节
//如果想存储字符串就必须申请内存,使用name_这个指针指向申请的内存
public:
person(const char* name)
{
name_ = new char[strlen(name) + 1];
strcpy(name_, name);
cout << __FUNCTION__ << endl;
}
~person()
{
cout << __FUNCTION__ << endl;
delete[] name_;
name_ = nullptr;
}
void display()
{
cout << name_ << " " << endl;
}
};
class person1 {
char name_[128];//这是个字符数组,长度为128个字节,可以存储长度为127长度的字符串,字符串需要一个结束符
public:
person1(const char* name)
{
strcpy(name_, name);
cout << __FUNCTION__ << endl;
}
~person1()
{
cout << __FUNCTION__ << endl;
}
void display()
{
cout << name_ << " " << endl;
}
};
class person2 {
string name_;//string帮我们做好了内存申请和释放
public:
person2(const char* name)
{
name_.append(name);
cout << __FUNCTION__ << endl;
}
~person2()
{
cout << __FUNCTION__ << endl;
}
void display()
{
cout << name_ << " " << endl;
}
};
int main()
{
person p("Apple");
p.display();
person2 p1("Apple");
p1.display();
person2 p2("Apple");
p2.display();
return 0;
}