一、继承的概念
1. 面向对象中的继承指类之间的父子关系;
2. 子类拥有父类的所有成员变量和成员函数;
3. 子类就是一种特殊的父类;
4. 子类对象可以当作父类对象使用;
5. 子类可以拥有父类没有的方法和属性;
#include <cstdlib>
#include <iostream>
using namespace std;
class Parent
{
private:
int a;
public:
Parent()
{
a = 1000;
}
void print()
{
cout<<"a = "<<a<<endl;
}
};
class Child : Parent
{
};
int main(int argc, char *argv[])
{
Parent parent;
Child child;
parent.print();
child.print();
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
编译运行结果如下:
继承时的访问级别设定会影响到成员的访问级别。
注意:
1. C++中class的继承默认为private继承;
2. private继承的子类拥有父类的所有成员;
3. private继承使得父类的所有成员在子类中变为private成员;
C++中的访问级别与继承
public继承
父类成员在子类中保持原有访问级别;
private继承
父类成员在子类中变为private成员;
#include <cstdlib>
#include <iostream>
using namespace std;
class Parent
{
private:
int a;
public:
Parent()
{
a = 1000;
}
void print()
{
cout<<"a = "<<a<<endl;
}
};
class Child : public Parent
{
private:
int b;
public:
void set(int a, int b)
{
this->a = a;
this->b = b;
}
};
int main(int argc, char *argv[])
{
Parent parent;
Child child;
parent.print();
child.print();
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
编译运行结果如下:
类成员的访问级别只有public和private是否足够?
类的protected成员
1. protected成员可以在子类中被访问,但不能在外界被访问;
2. protected成员的访问权限介于public和private之间;
#include <cstdlib>
#include <iostream>
using namespace std;
class Parent
{
protected:
int a;
public:
Parent()
{
a = 1000;
}
void print()
{
cout<<"a = "<<a<<endl;
}
};
class Child : public Parent
{
protected:
int b;
public:
void set(int a, int b)
{
this->a = a;
this->b = b;
}
};
int main(int argc, char *argv[])
{
Parent parent;
Child child;
parent.print();
child.print();
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
编译运行结果如下:
如何恰当的使用public,protected和private为成员声明访问级别??
类成员访问级别设置的原则
1. 需要被外界访问的成员直接设置为public;
2. 只能在当前类中访问的成员设置为private;
3. 只能在当前类和子类中访问的成员设置为protected;
#include <cstdlib>
#include <iostream>
using namespace std;
class A
{
private:
int a;
protected:
int b;
public:
int c;
A()
{
a = 0;
b = 0;
c = 0;
}
void set(int a, int b, int c)
{
this->a = a;
this->b = b;
this->c = c;
}
};
//B通过public继承A所有成员,并且成员的访问级别保持不变
class B : public A
{
public:
void print()
{
cout<<"a = "<<a; //Error
cout<<"b = "<<b;
cout<<"c = "<<endl;
}
};
//C通过protected继承A所有成员
class C : protected A
{
public:
void print()
{
cout<<"a = "<<a; //Error
cout<<"b = "<<b;
cout<<"c = "<<endl;
}
};
//C通过private继承A所有成员
class D : private A
{
public:
void print()
{
cout<<"a = "<<a; //Error
cout<<"b = "<<b;
cout<<"c = "<<endl;
}
};
int main(int argc, char *argv[])
{
A aa;
B bb;
C cc;
D dd;
aa.c = 100;
bb.c = 100;
cc.c = 100; //Error
dd.c = 100; //Error
aa.set(1, 2, 3);
bb.set(10, 20, 30);
cc.set(40, 50, 60); //Error
dd.set(70, 80, 90); //Error
bb.print();
cc.print();
dd.print();
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
编译运行结果如下:
小结:
1. 继承是一种类之间的关系,子类是一种特殊的父类;
2. 子类通过继承可以得到父类的所有成员;
3. private成员可以被子类继承但不能被子类访问;
4. protected成员只能在当前类和子类中被访问;
5. 不同的继承方式可能改变继承成员的访问属性;