类对象成员的初始化
#include<bits/stdc++.h>
using namespace std;
/**
* 类对象成员初始化
* */
class StudentID {
public:
int getID() {
return value;
}
StudentID(int id=0) {
value = id;
printf("student id: %d\n", value);
}
~StudentID() {
printf("destruct id: %d\n", value);
}
private:
int value;
};
class Student {
char name[20];
StudentID id;
public:
Student(char *pName="noName", int ssID = 0): id(ssID) {
printf("construct student %s\n", pName);
strncpy(name, pName, sizeof(name));
name[sizeof(name)-1] = '\0';
// StudentID(ssID); // 错误,实际上定义了一个对象成员,但是之前已经调用了默认的构造函数了
}
~Student() {
printf("destruct name %s id: %d\n", name, id.getID());
}
void display() {
printf("student name:%s id: %d\n", name, id.getID());
}
};
int main() {
char name[20] = "console";
Student s(name, 2019);
s.display();
return 0;
}
类对象成员的构造顺序
#include<bits/stdc++.h>
using namespace std;
/**
* 类对象成员的构造顺序
* */
class A {
int a;
public:
A(int i) {
a = i;
printf("construct A a=%d\n", a);
}
};
class B {
int b;
public:
B(int i) {
b = i;
printf("construct B b=%d\n", b);
}
};
class C {
A a1, a2;
B b1, b2;
public:
C(int i1, int i2, int i3, int i4) :b1(i1), a1(i2), b2(i3), a2(i4) {
}
};
int main() {
C x(1, 2, 3, 4);
return 0;
}
输出顺序应该是声明顺序,而不是构造函数中初始化列表的顺序
2 4 1 3