结论:
类需要先定义,而后才能被实例化,但是实际存在一种场景是:两个类需要相互引用或相互成为类中的子对象成员时,就无法先定义使用,在编译环节就出现错误导致编译失败,这时就需要用到前向声明,此外,前向声明的类不能被实例化。
类的相互访问方式如下:
代码如下:
//CB类
//.h文件引用 CA头文件, .cpp无需引用 CA头文件,可访问 CA对象(.cpp 存在A的头文件)
//默认先调用 CB构造函数,再调用CA构造函数
-------------------------------.h文件----------------------------------
#include <iostream>
#include "B.h"
using namespace std;
class CA
{
private:
int a;
public:
CA();
~CA();
CB b;
void setA(int a);
int getA();
void ShowBData();
};
------------------------------.cpp文件-----------------------------------
#include "stdafx.h"
#include "A.h"
CA::CA()
{
cout << "CA Construct" << endl;
}
CA::~CA()
{
cout << "CA Destroy" << endl;
}
void CA::setA(int a)
{
this->a = a;
}
int CA::getA()
{
return a;
}
void CA::ShowBData()
{
cout << b.GetB() << endl;
}
//头文件 提前引入 class CA
//.cpp文件 加入CA的头文件
//CB中不能出现CA的对象,可以是指针,或者引用
--------------------------------------------.h文件-----------------------------------
#pragma once
#include<iostream>
using namespace std;
class CA;
class CB
{
private:
int b;
public:
CB();
~CB();
CA *a;
int GetB();
void SetB(int b);
void ShowAData();
};
---------------------------------------.cpp文件-------------------------------
#include "stdafx.h"
#include "B.h"
#include "A.h"
CB::CB()
{
cout << "CB Construct" << endl;
}
CB::~CB()
{
cout << "CB Destroy" << endl;
}
int CB::GetB()
{
return b;
}
void CB::SetB(int b)
{
this->b = b;
}
void CB::ShowAData()
{
cout << a->getA() << endl;
}
//定义CA,CB对象,并给变量赋值
#include "stdafx.h"
#include <iostream>
#include "A.h"
#include "B.h"
using namespace std;
int main()
{
CA a;
CB b;
a.setA(1);
b.SetB(2);
a.b = b;
b.a = &a;
a.ShowBData();
b.ShowAData();
while (1)
{
}
return 0;
}