如何从类中实例化的对象访问私有变量
问题描述:
我试图更改一个类中的一个私有变量,该类在对象内部初始化。
我的意图可以从下面的简单例子中得出。
从 obj
调用增量$ c>应该增加
BaseClass :: stuff
。
I am trying to change a private variable of a class inside an object, which is initialized inside that class.
My intention can be drawn from the simple example below.
the Increment
called from obj
should increase the BaseClass::stuff
.
template <typename ObjectType>
class BaseClass{
public:
int Increment(){
return obj.Increment();
}
private:
int stuff = 0;
ObjectType obj;
};
class ObjectType{
public:
int Increment ()
{
return BaseClass<ObjectType>::stuff++;
};
};
int main () {
BaseClass<ObjectType> base;
base.Increment(); // should increase stuff by 1;
}
我可以想到的一种方法是将参数传递给 obj.Increment()
。
One way I can think of is passing stuff as parameter to obj.Increment()
.
有没有一种方法,我可以实现这个而不传递作为参数?
Is there a way I can achieve this without passing it as a parameter?
答
您的示例有一些错误。
修复并添加了朋友
说明符后,应该如下所示:
Your example had a few errors.
Once fixed and added a friend
specifier, it should look like this:
template <typename ObjectType>
class BaseClass{
public:
friend ObjectType;
int Increment(){
return obj.Increment();
}
private:
static int stuff;
ObjectType obj;
};
template<typename T>
int BaseClass<T>::stuff = 0;
class ObjectType{
public:
int Increment ()
{
return BaseClass<ObjectType>::stuff++;
};
};
int main () {
BaseClass<ObjectType> base;
base.Increment(); // should increase stuff by 1;
}