77.初始化数据,如果类中有其他类,需要重写构造函数

 1 #include <iostream>
 2 #include <cstdlib>
 3 #include <string>
 4 using namespace std;
 5 
 6 //初始化数据的时候,如果类中引用其他类,需要重写构造函数,int也是类
 7 class myclass
 8 {
 9 public:
10     int x;
11     int y;
12 
13 public:
14     myclass(int a,int b) : x(a),y(b)
15     {
16 
17     }
18 };
19 
20 
21 union myu
22 {
23     string str1;
24     int a;
25     int b;
26     myu()
27     {
28         new(&str1)string;//调用构造函数
29     }
30     ~myu()
31     {
32         str1.~basic_string();//析构
33     }
34 };
35 
36 void main()
37 {
38     myu my;
39     my.str1 = "234";
40     cout << my.str1 << endl;
41     
42     myclass *p = new myclass[2]{ {1,2},{3,4} };
43     for (int i = 0; i < 2; i++)
44     {
45         cout << p[i].x << " " << p[i].y << endl;
46     }
47     cin.get();
48 }
原文地址:https://www.cnblogs.com/xiaochi/p/8576790.html