多态为C++中面向对象三大特征之一,通俗地讲,就是多种形态。作用为完成某个行为,当不同(具有继承关系)的对象去完成时会产生不同的状态。
在基类中被virtual修饰并且在派生类中重新定义的类成员函数。
class Base
{
public:
virtual void Print()
{
cout << "Base::Print()" << endl;
}
};
class Derive :public Base
{
virtual void Print()
{
cout << "Derive::Print()" << endl;
}
};
//void Func(Base* b)
void Func(Base& b)
{
//b->Print();
b.Print();
}
int main()
{
Base b;
Derive d;
Func(b);
Func(d);
/*Func(&b);
Func(&d);*/
return 0;
}
当派生类重写基类虚函数时,重写的虚函数与基类虚函数返回值类型不同。即基类虚函数返回基类对象的指
针或者引用,派生类虚函数返回派生类对象的指针或者引用。返回类型除了基类和派生类(或具有其他继承关系的基类和派生类)的指针或者引用,其他的类型都不构成协变。
class A{};
class B :public A{};
class Base
{
public:
virtual A* Func1()
{
return new A;
}
virtual Base* Func2()
{
return new Base;
}
};
class Derive :public Base
{
virtual B* Func1()
{
return new B;
}
virtual Derive* Func2()
{
return new Derive;
}
};
class Base
{
public:
virtual ~Base()
{
cout << "~Base()" << endl;
}
};
class Derive :public Base
{
public:
virtual ~Derive()
{
cout << "~Derive()" << endl;
}
};
int main()
{
Base* p1 = new Base;
Base* p2 = new Derive;
delete p1;
delete p2;
return 0;
}
检查用override修饰的派生类虚函数是否重写了基类的某个虚函数,如果没有重写则报错。
class Base
{
public:
virtual void Func()
{
cout << "Base::Func()" << endl;
}
};
class Derive :public Base
{
public:
virtual void Func1() override
{
cout << "Derive::Func()" << endl;
}
};
修饰虚函数,表明该虚函数不能被重写。
class Base
{
public:
virtual void Func()final
{
cout << "Base::Func()" << endl;
}
};
class Derive :public Base
{
public:
virtual void Func()
{
cout << "Derive::Func()" << endl;
}
};
class Base
{
public:
virtual void Func() = 0;
};
class Derive :public Base
{
public:
virtual void Func()
{
cout << "Derive::Func()" << endl;
}
};
int main()
{
//Base b;
Derive d;
d.Func();
return 0;
}
class Base
{
public:
virtual void Func() = 0;
};
class Derive :public Base
{
public:
/*virtual void Func()
{
cout << "Derive::Func()" << endl;
}*/
};
int main()
{
Base b;
Derive d;
d.Func();
return 0;
}
class Base
{
virtual void Func1()
{
cout << "Base::virtual void Func1()" << endl;
}
/*virtual void Func2()
{
cout << "Base::virtual void Func2()" << endl;
}
void Func3()
{
cout << "Base::void Func3()" << endl;
}*/
private:
int _b = 1;
};
//class Derive :public Base
//{
// virtual void Func1()
// {
// cout << "Derive::virtual void Func1()" << endl;
// }
//private:
// int _d = 2;
//};
int main()
{
Base b;
cout << sizeof(b) << endl;
//Derive d;
return 0;
}
本文到这里就结束了,如有错误或者不清楚的地方欢迎评论或者私信
创作不易,如果觉得博主写得不错,请务必点赞、收藏加关注