结构体中使用string
来源:互联网 发布:淘宝上开店在哪里进货 编辑:程序博客网 时间:2024/05/21 10:57
1. malloc只是负责申请一块内存,没有任何其他动作。
2. 直接声明结构体或者new 一个结构体指针,会调用默认构造函数。如果结构中包含类,同样会调用成员类的默认构造函数。
3. 程序中的内存错误是因为使用malloc分配一个结构体内存,但是string是一个类。并没有调用string的构造函数,所以string在malloc之后没有正确构造,导致使用时段错误。
---------------------------------------
下面测试程序前两个直接声明结构体和new出来的,都可以正确赋值,但是malloc的那块,赋值就段错误。
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <string>#include <iostream>using namespace std;class A{public:A(){cout << "construct in A" << endl;}};typedef struct tagTEST{A a;string s;char* ch;int i;} TEST;int main(){TEST t;t.s = "111";cout << t.s << endl;TEST* pNewTest = new TEST;pNewTest->s = "222";cout << pNewTest->s << endl;TEST* pMallocTest = (TEST*)malloc(sizeof(TEST) * 1);pMallocTest->s = "333";cout << pMallocTest->s << endl;return 0;}
0 0
- 结构体中使用string
- 结构体中使用string
- 结构体中使用string的错误
- 结构体中定义string变量
- 结构体中存在string类型成员
- 结构体中string类型成员
- matlab中使用结构体
- matlab中使用结构体
- matlab中使用结构体
- matlab中使用结构体
- 结构体中使用函数
- matlab中使用结构体
- matlab中使用结构体
- matlab中结构体使用
- 谈结构体中std::string所占的空间
- 给结构体中string赋值时,程序被中断
- Swift中获取String结构体字符串的长度
- 给结构体中std::string成员变量赋值失败
- C++之练习题38
- HBase 0.94.21 zookeeper-3.4.6 分布式安装
- 包装机与自然资源的关系
- Android UI布局如何固定底部元素
- 二分查找
- 结构体中使用string
- R12.2新特性:弹性域值集安全策略
- redis缓存集群及集群负载均衡方案设计
- POJ 1651 Multiplication Puzzle (区间dp)
- Centos安装nginx服务
- Gdb调试多进程程序
- IOS中http请求使用cookie
- 【HDU2865】构造矩阵+Burnside定理+欧拉函数类似poj2888
- Qt中的信号与槽机制