如何从类中实例化的对象访问私有变量 [英] How to access private variable from object instantiated inside class
本文介绍了如何从类中实例化的对象访问私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图更改一个类中的一个私有变量,该类在对象内部初始化。
我的意图可以从下面的简单例子中得出。
从 obj
调用增量应该增加
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;
}
这篇关于如何从类中实例化的对象访问私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文