1.
- 私有成员变量或函数在类的外部是不可访问的,甚至是不可查看的。只有类和友元函数可以访问私有成员。
- 保护成员变量或函数与私有成员十分相似,但有一点不同,保护成员在派生类(即子类)中是可访问的。
2.
继承中的特点
有public, protected, private三种继承方式,它们相应地改变了基类成员的访问属性。
1.public 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:public, protected, private
2.protected 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:protected, protected, private
3.private 继承:基类 public 成员,protected 成员,private 成员的访问属性在派生类中分别变成:private, private, private
但无论哪种继承方式,上面两点都没有改变:
1.private 成员只能被本类成员(类内)和友元访问,不能被派生类访问;
2.protected 成员可以被派生类访问。
3.
以下是一个简单的测试类的例子。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Point{
private:
int distance;
int x,y;
public:
Point(){
}
Point(int xx,int yy){
x=xx;
y=yy;
cout<<"Point object has been created!"<<endl;
}
void setPoint(int xx,int yy);
int showDistance(){
return x*y;
}
};
class colorPoint:public Point{
private:
string color{"Black"};//如果想要使用基类的构造函数并且初始化派生类的某个成员,采用初始化表达式的方式
public:
//写法1:此写法可以同时调用基类的构造函数和初始化派生类成员。
//这里如果想要使用基类的构造函数,需要在派生类中显示说明 ,将所需要的参数写在函数的后边
colorPoint(int xx,int yy,string zz):Point(xx,yy),color(zz){
cout<<"colorPoint object has been created!"<<endl;
}
//重载函数,先不设置color也可以,将会采用默认的color。
colorPoint(int xx,int yy):Point(xx,yy){
cout<<"colorPoint object has been created!"<<endl;
}
/*
//写法2:使用using使用基类构造函数,此写法无法初始化派生类的成员,需要采用初始化表达式如上
using Point::Point;
colorPoint(){
cout<<"colorPoint object has been created!"<<endl;
}
*/
void setColor(string Color){
color=Color;
}
string showColor(){
return color;
}
};
void Point::setPoint(int xx,int yy)
{
x=xx;
y=yy;
}
int main()
{
Point p1(1,1);
colorPoint cP1(13,13,"Green");
//cP1.setPoint(12,12);
//cP1.setColor("Green");
p1.setPoint(11,11);
cout<<p1.showDistance()<<endl;
cout<<cP1.showDistance()<<endl;
cout<<cP1.showColor()<<endl;
return 0;
}
输出:
Point object has been created!
Point object has been created!
colorPoint object has been created!
121
169
Green
--------------------------------
Process exited with return value 0
Press any key to continue . . .