C++结构体里面string类型赋值问题

发表于:2014-8-06 10:29

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:liuzhangheng    来源:51Testing软件测试网采编

#include<string>
using namespace std;
struct temp
{
string s;
};
int main()
{
const string p="aaa";
temp *q;
q=(struct temp*)malloc(sizeof(struct temp));
q->s=p;
}
  上述那种情况的赋值会导致程序中断
  需要用用new来分配内存,malloc不会调用结构函数
  结构体内的string不定长,不能动态分配内存。
#include<string>
using namespace std;
struct temp
{
string s;
};
int main()
{
const string p="aaa";
temp *q;
//q=(struct temp*)malloc(sizeof(struct temp));
q = new temp;
q->s=p;
  C++的结构体和类都有默认构造函数的,不写都会自动实现一个。
  malloc只是分配内存。
  new除了分配内存还会调用构造函数的。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号