a. 在C++的类的成员函数中,允许直接访问该类的对象的私有成员变量。
b. 在类的成员函数中可以访问同类型实例的私有变量。
c. 拷贝构造函数里,可以直接访问另外一个同类对象(引用)的私有成员。
d. 类的成员函数可以直接访问作为其参数的同类型对象的私有成员。
举例:
a.
#include <iostream>
using namespace std;class CTest
{
public:CTest();CTest(int x);int getX();void setX(int x);
private:int x;
};CTest::CTest(){}CTest::CTest(int x)
{this->x = x;
}int CTest::getX()
{return x;
}void CTest::setX(int x)
{this->x = x;
}int main ()
{CTest test(100);cout << test.getX() << endl;return 0;
}
b. #include <iostream>
using namespace std;class A
{
public:A(){x = 10;}void show(){cout << x << endl;}
private:int x;
};class CTest
{
public:CTest();CTest(int x);int getX();void setX(int x);void fun();
private:int x;
};CTest::CTest(){}CTest::CTest(int x)
{this->x = x;
}int CTest::getX()
{return x;
}void CTest::setX(int x)
{this->x = x;
}void CTest::fun()
{CTest c;c.x = 100;cout << c.x << endl;//在类的成员函数中不可以访问非同类型对象的私有变量/*A a;cout << a.x << endl;*/
}int main ()
{//CTest test(100);//cout << test.getX() << endl;CTest test;test.fun();return 0;
}
c. #include <iostream>
using namespace std;class CTest
{
public:CTest();CTest(int x);int getX();void setX(int x);void copy(CTest &test);
private:int x;
};CTest::CTest(){}CTest::CTest(int x)
{this->x = x;
}int CTest::getX()
{return x;
}void CTest::setX(int x)
{this->x = x;
}//拷贝构造函数里,可以直接访问另外一个同类对象(引用)的私有成员
void CTest::copy(CTest &test)
{this->x = test.x;
}int main ()
{CTest test(100);CTest a;a.copy(test);cout << a.getX() << endl;return 0;
}
d. #include <iostream>
using namespace std;class CTest
{
public:CTest();CTest(int x);int getX();void setX(int x);void copy(CTest test);
private:int x;
};CTest::CTest(){}CTest::CTest(int x)
{this->x = x;
}int CTest::getX()
{return x;
}void CTest::setX(int x)
{this->x = x;
}//类的成员函数可以直接访问作为其参数的同类型对象的私有成员
void CTest::copy(CTest test)
{this->x = test.x;
}int main ()
{CTest test(100);CTest a;a.copy(test);cout << a.getX() << endl;return 0;
}
解释: 私有是为了实现“对外”的信息隐藏,或者说保护,在类自己内部,有必要禁止私有变量的直接访问吗?
请记住你是在定义你的类,不是在用。
C++的访问修饰符的作用是以类为单位,而不是以对象为单位。
通俗的讲,同类的对象间可以“互相访问”对方的数据成员,只不过访问途径不是直接访问.
类体内的访问没有访问限制一说,即private函数可以访问public/protected/private成员函数或数据成员,同理,protected函数,public函数也可以任意访问该类体中定义的成员。public继承下,基类中的public和protected成员继承为该子类的public和protected成员(成员函数或数据成员),然后访问仍然按类内的无限制访问。
每个类的对象都有自己的存贮空间,用于存储内部变量和类成员;但同一个类的所有对象共享一组类方法,即每种方法只有一个源本。