如何在兩個類之間傳遞成員變數的值
阿新 • • 發佈:2019-02-18
本例是B類的的成員變數“m_getvariate” 得到A類的物件a的成員變數“m_betransed”的值,對值進行修改後,再把值賦給m_betransed。
1.B類構建公共函式——void getvalue(const int variate ) { m_getvariate = variate;},這個函式用來把A類的成員變數的值傳遞給B;
2.B類中的void changeValue( )函式來對變數的值進行修改;
3.B類構建公共函式——const int setValue( ){ return m_getvalue} 把值返回給B類。
示例程式碼:
#include <iostream> using namespace std; class B; class A { public: A( void ); void f_init(); void prinvariate(); private: int m_betransed; }; class B { public: void getvariate( int t_variate ); void changeValue(); int setvariate(); private: int m_getvariate; }; int main() { A *a; a= new A; a->prinvariate( ); return 0; } A::A() { f_init(); } void A::f_init() { m_betransed = 2; B * b ; b = new B; b->getvariate( m_betransed );//b->m_getvariate = 2 b->changeValue( );//b->m_getvariate = 3 m_betransed = b->setvariate();//A->m_betransed = 3 } void B::getvariate(int t_variate ) { m_getvariate = t_variate; } void A::prinvariate() { cout << m_betransed; } void B::changeValue() { ++m_getvariate; } int B::setvariate() { return m_getvariate; }