我正在课堂上学习朋友,我的问题是: 我想 funcC3()设置并永久更改C1 :: a值,怎么做? 我想全局函数 gfunc()能够做同样的事情,怎么样? 能否请你按照我的方式提供给我,因为在书中他们没有指明?
#include <iostream>
using namespace std;
class C2;
class C3
{
public:
void funcC3(int const& x)
{
cout << "in third class...: " << x << endl;
};
};
class C1
{
private:
int a;
public:
void funcC1()
{
cout << "inside C1 private thingie: " << a << endl;
};
int C1::getcha();
friend class C2;
friend int gfunc(int chair);
friend void C3::funcC3(int const& a);
};
int C1::getcha()
{
return a;
};
class C2
{
public:
int a;
};
**int gfunc(int ch)**
{
int chair = ch;
return chair;
};
**int main()**
{
C1 obj1;
C3 obj3;
obj3.funcC3(10);
obj1.funcC1();
gfunc(12);
cout << C1.geta() << endl;
system("pause");
}
答案 0 :(得分:0)
我希望funcC3()设置并永久更改C1 :: a值,该怎么做 它?
在C1中将其声明为友元函数:
class C1; //forward declaration
class C3
{
//...
void funcC3( C1& c);
};
class C1
{
//...
private:
int a;
friend void C3::funcC3( C1&);
};
void C3::funcC3( C1& c) { c.a = 100;}
我希望全局函数gfunc()能够做到这一点,怎么做?
与上述相同:
class C1;
void gfunc( C1& c);
class C1 {
//...
private:
int a;
friend void gfunc( C1& c);
};
void gfunc( C1& c) { c.a = 100;}