c++ 类的访问权限探讨(四)

2014-11-24 07:13:37 · 作者: · 浏览: 2
public成员
int derived_public_member(apple &other)
{
return other.m_count;
}
// 访问子类的public函数
int derived_public_func(apple &other)
{
return other.count();
}
//// 访问子类的protected成员
//int derived_protected_member(apple &other)
//{
// return other.m_price;
//}
//// 访问子类的protected函数
//int derived_protected_func(apple &other)
//{
// return other.price();
//}
//// 访问子类的private成员
//int derived_private_member(apple &other)
//{
// return other.m_id;
//}
//// 访问子类的private函数
//int derived_private_func(apple &other)
//{
// return other.id();
//}
};
int main(int argc, char **argv)
{
fruit FRUIT_1;
apple APPLE_1(222, 200, 20);
cout << "FRUIT_1.derived_public_member(fruit FRUIT_1):" << FRUIT_1.derived_public_member(APPLE_1) << endl;
cout << "FRUIT_1.derived_public_func(fruit FRUIT_1):" << FRUIT_1.derived_public_func(APPLE_1) << endl;
//cout << "FRUIT_1.derived_protected_member(fruit FRUIT_1):" << FRUIT_1.derived_protected_member(APPLE_1) << endl;
//cout << "FRUIT_1.derived_protected_func(fruit FRUIT_1):" << FRUIT_1.derived_protected_func(APPLE_1) << endl;
//cout << "FRUIT_1.derived_private_member(fruit FRUIT_1):" << FRUIT_1.derived_private_member(APPLE_1) << endl;
//cout << "FRUIT_1.derived_private_func(fruit FRUIT_1):" << FRUIT_1.derived_private_func(APPLE_1) << endl;
}
编译报错,说fruit类不完全。看来,要在父类中调用子类的接口是不太可能的了,因为两者是继承关系,父类要调用子类的接口,必须先定义子类,但是子类的定义依赖父类的定义,所以这样就陷入类似死锁的情况。不过这种需求也是没有必要的。
总结一下:
(1)类域中,可以访问自身对象和此类的外部对象的所有成员和接口。
(2)继承关系的类域中,子类只能访问自身对象的基类的 public 和 protected 成员和接口
(3)继承关系的类域中,子类仅能访问其他的基类对象的 public 成员和接口
(4)继承关系的类域和,父类不能访问任何子类的成员和接口
(5)非继承关系的类域 以及 非类域中,仅能访问类对象的public成员和接口。