评论

收藏

[C++] C++类的拷贝与结构体的拷贝

编程语言 编程语言 发布于:2021-07-14 10:03 | 阅读数:278 | 评论:0

#include<iostream>
#include<cstdlib>
using namespace std;
struct obj {
string innerstring;
};
struct c_obj {
char* string;
size_t length;
};
int main(void) {
// c++类的优势可以体现在内存的动态上
struct obj a_obj, b_obj;
a_obj.innerstring = "a_obj";
b_obj.innerstring = "b_obj";
cout << "a_obj   " << a_obj.innerstring << endl;
cout << "b_obj  " << b_obj.innerstring << endl;
a_obj = b_obj;
cout << "a_obj   " << a_obj.innerstring << endl;
cout << "b_obj  " << b_obj.innerstring << endl;
b_obj.innerstring = "123";
cout << "a_obj   " << a_obj.innerstring << endl;
cout << "b_obj  " << b_obj.innerstring << endl;
//如果使用c语言的结构体造成的麻烦是如果要实现拷贝
//则需要新的结构体变量内的指针申请空间,否则它们将会指向同一块内存,达不到拷贝的效果
//例如
struct c_obj a_c_obj, b_c_obj;
a_c_obj.length = 5;
a_c_obj.string = (char*)malloc(sizeof(char) * a_c_obj.length);
a_c_obj.string[0] = '1';
a_c_obj.string[1] = '2';
a_c_obj.string[2] = '3';
a_c_obj.string[3] = '4';
a_c_obj.string[4] = '\0';
printf("%s\n", a_c_obj.string);
//如果直接将a_c_obj赋值给b_c_obj
b_c_obj = a_c_obj;
printf("%s\n", b_c_obj.string);
//如果更改b_c_obj.string那么a_c_obj.string也会改变
b_c_obj.string[0] = 'c';
b_c_obj.string[1] = 'h';
b_c_obj.string[2] = 'a';
b_c_obj.string[3] = 'n';
b_c_obj.string[4] = '\0';
printf("%s\n", a_c_obj.string);
printf("%s\n", b_c_obj.string);
return 0;
}

关注下面的标签,发现更多相似文章