Member objects - why are only public variables accessible?
In t开发者_如何学Gohe below code why should the variable i be public from class a? Why can't it be private or protected? I guess I am missing some basics of member objects. is it ?
#include <iostream>
class a
{
public:
int i;
};
class b
{
private:
a a1;
public:
void show()
{
a1.i=5;
std::cout << a1.i;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
b b1;
b1.show();
return 0;
}
This is not a nested class. It's just a class that happens to have a member variable whose type is another class. So the normal rules apply.
a and b are not nested.
'nested' would mean this:
class b
{
class a
{
};
};
So what you are doing is simply creating an instance of a inside b. So b has the same access to a as you would have to a if you would define it in your main function.
Public members can be accessed by anything. Protected members can only be accessed by derived classes and friends. Private memebers can only be accessed by friends. As b is neither a derived class nor friend of a, it can only view public members. If you wanted a.i to be protected, A must either contain friend b
, or b must inherit from a.
class b;
class a {
friend b;
int i;
};
or
class b : public a {
You are saying that just because class b includes a class a object it should be allowed to access private members of class a? There wouldn't be a lot of point in privacy if that were how things worked. I declare things private in my class so that you don't have to worry about them, and so I can change the private members of my class without breaking your code. None of that would work if what you are asking for were true.
Your classes are not nested. Only members of the same class or firends can access private variables. Since "b" is not a member of or a friend of "a" you can only access the variable "i" by making it public or using geter and setter methods. See: http://www.cplusplus.com/doc/tutorial/classes/ an example of a setter method is:
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
int main () {
CRectangle rect, rectb;
rect.set_values (3,4);
rectb.set_values (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
精彩评论