C++ 的几个面向对象的概念(一)
抽象类
- 是一个带有纯虚函数的类;
- 不能被实例化
class AbstractClass
{
virtual int sayHello() = 0;
};
Some Questions
- 抽象类是干嘛的?
通俗讲,抽象的对,代码越容易理解,代码复用率越高,开发效率越高。
哪个大佬说过:什么事情都抽象,就显得什么事情都对了(当然是含贬义的)
- 什么是纯虚函数? 抽象类中能包含非纯虚函数吗?
看到上面的例子了吗?它是一个虚函数,然后它没有实现,最后 = 0。^^抽象类中是否能包含非纯虚函数,去自己试试!!!
虚基类
虚基类被派生类虚继承,能够解决多重继承引入的二义性问题。
由菱形继承带来的二义性的问题,如下代码,编译器无法识别 Child 对象 getName 时是来自 ParentA 的 name 还是来自 ParentB 的 name,出现错误 reference to ‘name’ is ambiguous。
class Base
{
protected:
string name;
};
class ParentA: public Base
{
protected:
int age;
};
class ParentB: public Base
{
protected:
int grade;
};
class Child: public ParentA, public ParentB
{
public:
void getName() const {
cout << "Child name = " << name << endl;
}
};
怎么修改?当然可以通过 ParentA::name, ParentB::name 来区分,但对于带有洁癖的程序员肯定是不能满足,而虚继承的方式就显得干净多了^^
class Base
{
protected:
string name;
};
class ParentA: virtual public Base
{
protected:
int age;
};
class ParentB: virtual public Base
{
protected:
int grade;
};
class Child: public ParentA, public ParentB
{
public:
void getName() const {
cout << "Child name = " << name << endl;
}
void setName(const string& name) {
this->name = name;
}
};
int main()
{
Child c;
c.setName("中国");
c.getName();
return 0;
}
运行结果:
Child name = 中国