C++多态的两种使用方式

记在这里当笔记吧,大牛们可以无视了。

语法上来说可以使用“引用”或者“指针”使用多态的特性,具体可看代码。值得注意的是,定义引用的时候需要初始化,不然报错。

#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/p/1727523.html