关于继承中对象指针的一些有关问题

关于继承中对象指针的一些问题。
本帖最后由 tyaathome 于 2014-02-13 15:37:07 编辑
最近在看刘伟老师写的设计模式,看到了合成复用原则这里
http://blog.****.net/lovelion/article/details/7563441

我看到了他画的uml类图,我想自己写一写试试能不能实现这种不违反开闭原则添加子类来添加功能。
然后piapiapia的写完了,一运行出问题了
代码如下
#include<iostream>
using namespace std;

class DBUtill
{
public:
    virtual void getConnection()
    {
        cout<<"basic getConnection()"<<endl;
    }
};

class OracleDBUtill : public DBUtill
{
public:
    virtual void getConnection()
    {
        cout<<"sub getConnection()"<<endl;
    }
};

class CustomerDAO
{
private:
    DBUtill utill;
public:
    CustomerDAO(DBUtill utill)
    {
        this->utill = utill;
    }
    ~CustomerDAO()
    {
    }
    void addCustomer()
    {
        utill.getConnection();
    }
};

int main()
{
    DBUtill d1;
    OracleDBUtill od1;
    CustomerDAO* c1 = new CustomerDAO(d1);
    CustomerDAO* c2 = new CustomerDAO(od1);
    c1->addCustomer();
    c2->addCustomer();
    return 0;
}

本来预期输出的是
basic getConnection()
sub getConnectio()
但是事与愿违,输出的是:
关于继承中对象指针的一些有关问题

然后我改成将DBUtill类的对象指针来初始化CustomerDAO类的对象,
代码如下:
#include<iostream>
using namespace std;

class DBUtill
{
public:
    virtual void getConnection()
    {
        cout<<"basic getConnection()"<<endl;
    }
};

class OracleDBUtill : public DBUtill
{
public:
    virtual void getConnection()
    {
        cout<<"sub getConnection()"<<endl;
    }
};

class CustomerDAO
{
private:
    DBUtill* utill;
public:
    CustomerDAO(DBUtill* utill)
    {
        this->utill = utill;
    }
    ~CustomerDAO()
    {
    }
    void addCustomer()
    {
        utill->getConnection();
    }
};

int main()
{
    DBUtill* d1= new DBUtill();
    OracleDBUtill* od1 = new OracleDBUtill();
    CustomerDAO* c1 = new CustomerDAO(d1);
    CustomerDAO* c2 = new CustomerDAO(od1);
    c1->addCustomer();
    c2->addCustomer();
    return 0;
}

得到想输出的结果:
关于继承中对象指针的一些有关问题

这是为什么?本人愚钝求指教。
------解决方案--------------------
DBUtill 改成 DBUtill& 就可以了。

对象传递 是有 object sliceing的。
需要用 引用。