B类中包含A类的对象a,a即对象成员。
初始化方法
#include <iostream>
using namespace std;
class A
{
int x;
friend class B;
public:
A(int a)
{
x = a;
cout << "Ax =" << x << endl;
}
};
class B
{
int z;
A a1, a2;
public:
B(int c1, int c2, int c3) :a2(c1), a1(c2)
{
z = c3;
cout << "Bz =" << z << endl;
}
};
int main()
{
B b(1, 2, 3);
}
输出结果
Ax =2
Ax =1
Bz =3
可以看出对象成员构造函数的调用顺序与对象成员在类中定义的次序相同,即B中的A a1,a2使得先构造a1对象。
错误分析
#include <iostream>
using namespace std;
class B;
class A
{
int x;
friend B;
public:
A(int a);
};
A::A(int a)
{
x = a;
cout << "Ax =" << x << endl;
}
class B
{
int z;
A a1, a2;
public:
B(int c1, int c2, int c3)
{
a2.x = c1;
a1.x = c2;
z = c3;
cout << "Bz =" << z << endl;
}
};
int main()
{
B b(1, 2, 3);
A a(4);
}
编译错误: 类不存在默认构造函数
修改编译问题的方法(并不是解决初始化问题)
法1增加无参构造函数
A() { cout << "Ax =" << x << endl;} //A中添加无参构造函数,否则B中的临时对象成员a1a2无相应构造函数
法2对有参构造函数初始化
A(int a=0); //B中a1a2的x均为0
这样编译通过,但输出结果 法1
Ax =-858993460
Ax =-858993460
Bz =3
Ax =4
法2
Ax =0
Ax =0
Bz =3
Ax =4
反正都不是预期的结果,正确的初始化方式还是最开始的那一种。