C + + A class calls a member variable/member function of another class __jquery

Source: Internet
Author: User

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;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.