If I have two classes for example as follows:
class A {...}
class B {...}
If I want to make class A
public to class B
, do I just make the 开发者_高级运维members of class A
public or I can just use public class A {...}
?
Is there a way to tell class B
for example that only class A
is public for you? In other words, can I make public classes to A
protected or private to others? Or, this is just a matter of deriving a class (inheritance)?
Thanks.
There's a substantial difference between making the class public and making its contents public.
If you define your class in an include file (.h file) then you are making your class public. Every other source file that includes this include file will know about this class, and can e.g. have a pointer to it.
The only way to make a class private, it to put its definition in a source (.cpp) file.
Even when you make a class public, you don't necessarily have to make the contents of your class public. The following example is an extreme one:
class MyClass
{
private:
MyClass();
~MyClass();
void setValue(int i);
int getValue() const;
};
If this definition is put in an include file, every other source can refer to (have a pointer to) this class, but since all the methods in the class are private, no other source may construct it, destruct it, set its value or get its value.
You make the contents of a class public by putting methods from it in the 'public' part of the class definition, like this:
class MyClass
{
public:
MyClass();
~MyClass();
int getValue() const;
private:
void setValue(int i);
};
Now everybody may construct and destruct instances of this class, and may even get the value. Setting the value however, is not public, so nobody is able to set the value (except the class itself).
If you want to make the class public to only some other class of your application, but not to the complete application, you should declare that other class a friend, e.g.:
class SomeOtherClass;
class MyClass
{
friend SomeOtherClass;
public:
MyClass();
~MyClass();
int getValue() const;
private:
void setValue(int i);
};
Now, SomeOtherClass may access all the private methods from MyClass, so it may call setValue to set the value of MyClass. All the other classes are still limited to the public methods.
Unfortunately, there is no way in C++ to make only a part of your class public to a limited set of other classes. So, if you make another class a friend, it is able to access all private methods. Therefore, limit the number of friends.
You can use friendship.
class A { friend class B; private: int x; };
class B { B() { A a; a.x = 0; // legal };
If B has a strong interdependence to A, i suggest you use a nested class. Fortunately, nested class can be protected or private.
class A {
protected:
// the class A::B is visible from A and its
// inherited classes, but not to others, just
// like a protected member.
class B {
public:
int yay_another_public_member();
};
public:
int yay_a_public_member();
};
精彩评论