1、
class base
{
public:
base(int i = 1):pri(i) {}
int fun(base &b)
{
return pri + b.pri;
}
private:
int pri;
};
void fun(base &b)
{
cout << b.pri << endl; //error:can't access pri of b
}
在base::fun(base &b)中可以访问b的私有变量pri。因为: 所谓私有,是针对类的,而不是具体的对象。什么意思?
private成员只能由基类的成员和友元访问(c++ primer)。此处的b.pri仍然在基类的成员函数中。
2、
今天再次遇到类似疑惑。如下代码,要重载"=="。
class object
{
public:
object(int i):pri_val(i) {}
bool operator==(const object &obj1);
int get_private_value(void) const { return pri_val; }
private:
int pri_val;
};
bool object::operator==(const object &obj1)
{
return (pri_val == obj1.pri_val);
}
要获取obj1对象的pri_val,需要用函数get_private_value吗?不需要,可以用obj1直接访问,因为访问权限是针对类的,而非对象,函数operator==()仍在object类的范围内,仍属于该类的成员函数。
Members defined after a private label are not accessible to code that uses the class.
The private members are accessible only to the members and friends of the base class. A derived class has the same access as any other part of the program to thepublic and private members of its base class: It may access the public members and has no access to the privatemembers.
3、
#include <iostream>
using namespace std;
class base
{
public:
base(int i=1, int j=2, int k=3):pri(i), pro(j), pub(k) {}
private:
int pri;
protected:
int pro;
public:
int pub;
};
class derived: public base
{
public:
derived(int i1, int i2, int i3):base(i1, i2, i3) {}
void fun(base &b)
{
//cout << "pri = " << pri << endl; //error
//cout << pri + b.pri << endl; //error
//cout << pri + base::pri << endl; //error
//cout << pro + b.pro << endl; //error
cout << base::pro << endl;
cout << pub + b.pub << endl;
cout << pub + base::pub << endl;
}
};
int main()
{
base b;
derived d(4,5,6);
d.fun(b);
return 0;
}
输出:5,9,12
因为类成员的访问属性是针对类的,而非对象。
"cout << pri << endl;"报错为:int base::pri is private。说明父类的private成员并没有被子类继承。
private成员只能被该类的成员函数和该类的友元访问,不能被使用该类的user访问,可知访问属性是针对类而非对象,无论是b.pri还是base::pri,要访问其他类的private成员都是非法的,除非是该类的友元。
protected的定义:protected成员可以被继承;像private成员一样,不可以被类的user访问;像public成员,一样可以被子类访问。由cout << base::pro << endl;输出5可知,被子类访问的是子类自己的继承自父类的protected成员。