Sometimes, there is no inherited relationship between two classes, but one class needs to refer to a member variable or member function in another class. How to do it.
Suppose you've created two classes a, B.
Class A
{public
:
A ();
~a ();
Public:
int nadd;
int add ();
};
Class B
{public
:
b ();
~b ();
Public:
int nadd;
int x;
};
Now you need to call the member variable B::nadd and b::x of Class B in the member function of Class A so that A::nadd and B::nadd are added, so you only need to include the header file of Class B in the. cpp file of Class A B.h
A.cpp
#include "stdafx.h"
#include "A.h"
#include "B.h"//header file containing class B
a::a ()
{
Nadd = 6;//Initialization
}
a::~a ()
{
}
int A::add ()
{
B bb;//instantiate an object
bb.x = 5;//assigns an int result to a member variable in the object
;
result = Nadd + bb.nadd-bb.x;//calls the member variable in BB (constructor in B initializes b::nadd=3) return result
;
}
The main function calls add ();
#include "stdafx.h"
#include "A.h"
#include "B.h"
#include <iostream>
using namespace std;
int _tmain (int argc, _tchar* argv[])
{
A AA;
int result = Aa.add ();
cout<< result;
System ("pause");
return 0;
}