记在这里当笔记吧,大牛们可以无视了。
语法上来说可以使用“引用”或者“指针”使用多态的特性,具体可看代码。值得注意的是,定义引用的时候需要初始化,不然报错。
#include <iostream>
using namespace std;
class Materials
{
public:
Materials(){}
~Materials(){}
virtual void Print();
protected:
private:
};
void Materials::Print()
{
cout<<"Materials"<<endl;
}
class Books : public Materials
{
public:
Books(){}
~Books(){}
void Print();
protected:
private:
};
void Books::Print()
{
cout<<"Books"<<endl;
}
int main(
{
Materials thing1;
Books book1;
thing1 = book1;
thing1.Print(); //将输出Materials,这应该不是我们想要的结果。可以这么理解,thing1 就是Materials类型的, thing1 = book1;其在内存空间里的所占的位置的固定的。所以无法改变。
//Materials &thing2; 这样的代码就出错了,必须初始化引用
Materials &thing2 = book1;
thing2.Print(); //将输出Books,这是使用多态的一种正确表现形式
Materials *thing2 = &book1;
thing2->Print(); //将输出Books,这是使用多态的另一种正确表现形式
return 0;
}
原文链接: https://www.cnblogs.com/dawn/archive/2010/05/04/1727523.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/10560
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!