使用多态重置指针

时间:2017-04-26 13:37:40

标签: c++ pointers polymorphism reset

这是一个即时消息:Base * ptr = new Derived() ;

使用ptr后,我想重置它。

为什么在基类成员执行*ptr = Derived() ;时,不会重置派生类成员?

在一个完整的例子中亲自看看:

#include <iostream>
#include <vector>

void print_array(const std::vector<int> & vec, const std::string & name = "" )
{
    std::cout << name << " => [ " ;
    for (unsigned i = 0; i < vec.size(); ++i)
    {
        std::cout << vec[i] << " " ;
    }
    std::cout << "]" << std::endl ;
}

void do_stuff(std::vector<int> & vec, unsigned size)
{
    vec.resize(size) ;
    std::fill(vec.begin(), vec.end(), size) ;
}

class Base
{
public:
    std::vector<int> base ;

    Base() {}
    virtual ~Base() {}
};

class Derived : public Base
{
public:
    std::vector<int> derv ;

    Derived() {}
    virtual ~Derived() {}
};


int main()
{
    // Working but without polymorphism
    // Derived * ptr = new Derived() ;

    //Non-working
    Base * ptr = new Derived() ;

    std::vector<int> & vecbase = static_cast<Derived*>(ptr)->base ;
    std::vector<int> & vecderv = static_cast<Derived*>(ptr)->derv ;

    print_array(vecbase, "vecbase") ;
    print_array(vecderv, "vecderv") ;
    do_stuff(vecbase, 3) ;
    do_stuff(vecderv, 3) ;
    print_array(vecbase, "vecbase") ;
    print_array(vecderv, "vecderv") ;

    // Non-working
    *ptr = Derived() ;

    // Working but non-optimal
    // delete ptr ;
    // ptr = new Derived() ;

    print_array(vecbase, "vecbase") ;
    print_array(vecderv, "vecderv") ;
    do_stuff(vecbase, 5) ;
    do_stuff(vecderv, 5) ;
    print_array(vecbase, "vecbase") ;
    print_array(vecderv, "vecderv") ;

    return 0;
}

当前输出:

vecbase => [ ]
vecderv => [ ]
vecbase => [ 3 3 3 ]
vecderv => [ 3 3 3 ]
vecbase => [ ]
vecderv => [ 3 3 3 ]  <=
vecbase => [ 5 5 5 5 5 ]
vecderv => [ 5 5 5 5 5 ]

预期产出:

vecbase => [ ]
vecderv => [ ]
vecbase => [ 3 3 3 ]
vecderv => [ 3 3 3 ]
vecbase => [ ]
vecderv => [ ] <=
vecbase => [ 5 5 5 5 5 ]
vecderv => [ 5 5 5 5 5 ]

[彼得编辑:]请注意,这不是切片,因为*p Derived,即使其静态类型为Base。] < / p>

0 个答案:

没有答案