#include <iostream>
using namespace std;
class A {
friend class B; //类B是类A的友元
public:
static
int value;
static
int num;
A(int x, int y) {
xp = x, yp = y;
value++;
cout <<
"调用构造:"
<< value << endl;
}
void displayA() {
cout << xp <<
","
<< yp << endl;
}
~A() {
num++;
cout <<
"调用析构:"
<< num << endl;
}
private:
int xp, yp;
};
class B {
public:
B(int x
1
, int x
2
) : mpt
1
(x
1
+
2
, x
2
-
2
), mpt
2
(x
1
, x
2
) {
cout <<
"调用构造\n"
; //mpt是类A的对象,有几个mpt,有关类A的操作便执行几次
}
void set(int m, int n);
void displayB();
~B() {
cout <<
"调用析构\n"
; //析构函数在类结束前调用,类结束的时候释放类申请的空间
}
private:
A mpt
1
, mpt
2
; //将A类的对象声明为B类的私有数据成员
};
int A::value =
0
;
int A::num =
0
;
void B::set(int m, int n) {
mpt
1
.xp = m *
2
, mpt
1
.yp = n /
2
;
}
void B::displayB() {
mpt
1
.displayA();
}
int main() {
B p(
10
,
20
);
cout <<
"Hello world!"
<< endl;
B displayB(); //通过友元,使类B输出类A的私有数据成员
return
0
;
}