C++的对象初始化方式

2021/11 04 22:11
方式一
int n=0;
void* p=0;
char c='a';
int n(0)

方式二
struct S1
{
  explicit S1(int n, int m):x(n), y(m) {}
  int x, y;
}
S1 s1(0,1);


方式三
int c1[2] = {0, 2};
char c2 = "message";
char c3 = {'m', 's', 'g'};
struct S
{
  int a,b;
}
S s={0,1}


c++03 不能初始化动态分配的pod对象,比如:
class C {
  int x[100];
  C();
}

也没有好办法初始化,只能这样:
std::vector <std::string> vs;
vs.push_back("alpha");
vs.push_back("beta");
vs.push_back("gamma");



而在C++11中加入了大括号(花括号`{`)初始化语法:

int a{0};
std::string s{"hello"};
std::string s2{s}; // copy
std::vector<std::string> vs {"alpha","bate","gamma"};
std::map<string, string> stars { { "s", "1" }, {"b", "2" }};
double* pd = new double[3] { 0.1, 0.2, 0.3};
class C {
  int x[4];
  C():x{0,1,2,3} {}
}


int n{}; // n等于0
int* p{}; // p等于nullptr
double d{}; // d等于0.0
char s[12] {}; // 12个连续的'\0';
char* p=new char[5] {}; // 5个'\0';

// 默认初始化为7
class C
{
  int x=7;
  int y[5] { 1, 2, 3, 4};
  std::string s("abc");
  char* p { nullptr };
}
以上形式等价于
class C
{
  int x;
  int y[5];
  std::string s;
  char* p;
  C(): s("abc"), x(7), y{1,2,3,4}, p(nullptr) {}
}

注意:
如果同时存在类成员初始化器和MemInit,后者会优先

struct Class53 {
    Class53(int v) :value(v) {
        printf("init=%d\n", v);
    }
    int value;
};

struct Class54 {
    Class53 c53obj1{ 5 };
    Class53 c53obj2{ 6 };
    Class54(): c53obj1(7) {}
};

Class54 p54;;
printf("%d\n", p54.c53obj1.value);
printf("%d\n", p54.c53obj2.value);
-------------打印出---------------
init=7
init=6
7
6