c++ 类的访问权限探讨
1. 在类域外部(非类域中),类对象访问自身接口和成员的限制,示例如下。[cpp]#include <stdlib.h>#include <iostream>using namespace std;class fruit{public:fruit(int id, int count, int price):m_count(count), m_price(price), m_id(id){}int count(){return m_count;}public:int m_count;protected:int price(){return m_price;}protected:int m_price;private:int id(){return m_id;}private:int m_id;};int main(int argc, char **argv){fruit FRUIT_1(000, 100, 15);cout << "FRUIT_1.m_count" << FRUIT_1.m_count << endl;cout << "FRUIT_1.count()" << FRUIT_1.count() << endl;cout << "FRUIT_1.m_price" << FRUIT_1.m_price << endl;cout << "FRUIT_1.price()" << FRUIT_1.price() << endl;cout << "FRUIT_1.m_id" << FRUIT_1.m_id << endl;cout << "FRUIT_1.id()" << FRUIT_1.id() << endl;}编译时报错,如下,可见在类域外部,类对象只能访问声明为public的接口。2. 在自身的类域中,类对象访问自身接口和成员的限制,示例如下:[cpp]#include <stdlib.h>#include <iostream>using namespace std;class fruit{public:fruit(int id, int count, int price):m_count(count), m_price(price), m_id(id){}int count(){return m_count;}// 访问自身类对象的public成员int other_count_member(fruit other){return other.m_count;}// 访问自身类对象的protected成员int other_price_member(fruit other){return other.m_price;}// 访问自身类类对象的private成员int other_id_member(fruit other){return other.m_id;}// 访问自身类对象的public函数int other_count_func(fruit other){return other.count();}// 访问自身类对象的protected函数int other_price_func(fruit other){return other.price();}// 访问自身类对象的private函数int other_id_func(fruit other){return other.id();}public:int m_count;protected:int price(){return m_price;}protected:int m_price;private:int id(){return m_id;}private:int m_id;};int main(int argc, char **argv){fruit FRUIT_1(111, 100, 10);fruit FRUIT_2(222, 200, 20);cout << "FRUIT_1.other_count_member(FRUIT_2):" << FRUIT_1.other_count_member(FRUIT_2) << endl;cout << "FRUIT_1.other_count_func(FRUIT_2):" << FRUIT_1.other_count_func(FRUIT_2) << endl;cout << "FRUIT_1.other_price_member(FRUIT_2):" << FRUIT_1.other_price_member(FRUIT_2) << endl;cout << "FRUIT_1.other_price_func(FRUIT_2):" << FRUIT_1.other_price_func(FRUIT_2) << endl;cout << "FRUIT_1.other_id_member(FRUIT_2):" << FRUIT_1.other_id_member(FRUIT_2) << endl;cout << "FRUIT_1.other_id_func(FRUIT_2):" << FRUIT_1.other_id_func(FRUIT_2) << endl;}可以正确编译,运行结果如下,可见在自身的类域中,类对象的所有成员和接口都是可见的。3. 在其他类域(非继承关系)中,类对象访问自身的接口和成员的限制,示例如下[cpp]#include <stdlib.h>#include <iostream>using namespace std;class book{public:book(int count, int price, int id):m_count(count), m_price(price), m_id(id){}int count(){return m_count;}publi补充:软件开发 , C++ ,
上一个:POJ2389:Bull Math
下一个:程序测试大小端
- 更多C/C++疑问解答:
- 关于c++的cout输出的问题。
- 在学校里学过C和C++,不过学的很一般,现在自学C#,会不会很难?
- 全国计算机二级C语言笔试题
- 已知某树有2个2度结点,3个3度结点,4个4度结点,问有几个叶子结点?
- c++数据结构内部排序问题,整数排序
- 2012九月计算机二级C语言全国题库,,急求急求
- 如果assert只有一个字符串作为参数,是什么意思呢?
- C语言中,哪些运算符具有左结合性,哪些具有右结合性,帮忙总结下,谢谢了!
- 为什么用结构体编写的程序输入是,0输不出来啊~~~
- 将IEEE—754的十六进制转化为十进制浮点类型,用C或C++都行,多谢各位大侠啊,非常感谢!
- 为什么这个程序求不出公式?
- 这个链表倒置的算法请大家分析下
- c语言函数库调用
- C语言unsigned int纠错
- C语言快排求解啊