看一个简单的例子:
#include <iostream>
using namespace std;
class Base
{
private:
string name;
string hobby;
string title;
};
void fun(Base a)
{
}
int main()
{
Base a;
fun(a);
return 0;
}
#include <iostream>
using namespace std;
class Base
{
private:
string name;
string hobby;
string title;
};
void fun(Base &a) //引用,不会有临时对象拷贝
{
}
int main()
{
Base a;
fun(a);
return 0;
}
对象切割
当把一个派生类的对象赋给一个基类的对象时,会发生对象切割(基类对象强制转换派生类对象也会发生)
例如
class Base
{
public:
virtual void fun()
{
cout << "Base fun() is Called." << endl;
}
};
class Derived:public Base
{
public:
void fun()
{
cout << "Derived fun() is called." << endl;
}
};
void fun1(Base b)
{
b.fun();
}
void fun2(Base *b)
{
b->fun();
}
void fun3(Base &b)
{
b.fun();
}
int main()
{
Derived d;
fun1(d);
fun2(&d);
fun3(d);
system("pause");
return 0;
}
可以看出,指针和地址传递可以实现虚函数的多态功能,在fun1(Base b)中, 传递Derived对象时发生了对象的切割,而对象的切割不会发生多态,所以调用Base当中对应的函数。
总结:多态的实现是通过指针和引用;而对象的转换只会造成对象切割,不能实现多态