Application structure
class Base
{
private: bool mEnabled;
public: bool getEnabled() { return mEnabled; }
};
class First : public Base;
{
// ...
};
class Second : public Base
{
Second() {
// I have to check First::mEnabled
}
}开发者_运维技巧;
class Manager
{
First obj1;
Second obj2;
};
I have some class manager which handles 2 another classes. And I have to check mEnabled variable in one such object from another. What's the right way? Would it be right if I'll make
static bool mEnabled;
static bool getEnabled();
p.s. There would be only 1 objects of this classes.
Instead of static you probably would check for getEnabled
in your class manager:
if( obj1.getEnabled() )
{
Second obj2;
}
The problem is that you want to get access to another class without any relation between them. So a more top-level class needs to create this relation.
You can invoke member functions on certain objects by preceding the function's name with the object's name and a dot:
void f(First& first)
{
if(first.getEnabled())
...
}
If you pass by pointer, use a ->
instead of the .
:
void f(First* first)
{
if(first->getEnabled())
...
}
So, you want to have two classes that don't know about eachother to communicate? While it is very possible assuming that your classes are only going to be instantiated once in you're apps lifetime, I wouldn't do it. It is bad practice.
I would definitely suggest letting the class know about the other as suggested in the above reply. If you need to do this though, you could use a global pointer to your class and assign it after it has been instantiated.
精彩评论