c++string类问题
老师说当要存的字符串小于16个字节时string在栈中开辟空间,大于16字节时在堆中开辟空间。然后网上好多小伙伴说string类的内部是这样的:classstring{…...
老师说当要存的字符串小于16个字节时string在栈中开辟空间,大于16字节时在堆中开辟空间。然后网上好多小伙伴说string类的内部是这样的:class string{……;char *p;……},其实不管多大都是在堆里。那下面这个程序会有运行错误,是什么原因?是p2在接文件中的p1数据时,成员string name的数据访问出了问题吗?
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Person
{
public:
Person(const char *name, int age)
{
this->name = name;
this->age = age;
}
Person(Person *p)
{
this->name = p->name;
this->age=p->age;
}
private:
string name;
int age;
};
int main()
{
Person p1("阿大",22);
ofstream ofs("D:\\data", ios::binary);
if (!ofs.is_open())
{
exit(0);
}
ofs.write((char*)&p1, sizeof(Person));//写入文件
ofs.close();
ifstream inf("D:\\data", ios::binary);
if (!inf.is_open())
{
exit(0);
}
Person p2("", 0);
inf.read((char*)&p2,sizeof(Person));
system("pause");
return 0;
} 展开
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Person
{
public:
Person(const char *name, int age)
{
this->name = name;
this->age = age;
}
Person(Person *p)
{
this->name = p->name;
this->age=p->age;
}
private:
string name;
int age;
};
int main()
{
Person p1("阿大",22);
ofstream ofs("D:\\data", ios::binary);
if (!ofs.is_open())
{
exit(0);
}
ofs.write((char*)&p1, sizeof(Person));//写入文件
ofs.close();
ifstream inf("D:\\data", ios::binary);
if (!inf.is_open())
{
exit(0);
}
Person p2("", 0);
inf.read((char*)&p2,sizeof(Person));
system("pause");
return 0;
} 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询