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

2014-11-24 07:13:37 · 作者: · 浏览: 0
1. 在类域外部(非类域中),类对象访问自身接口和成员的限制,示例如下。
[cpp]
#include
#include
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
#include
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
#include
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;
}
public:
int m_count;
protected:
int price()
{
return m_price;
}
protected:
int m_price;
private:
int id()
{
return m_id;
}
private:
int m_id;
};
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(book other)
{
return other.m_count;
}
// 访问其他类对象的public函数
int other_count_func(book