错误对象切片的原因是什么?

时间:2010-07-22 14:21:23

标签: c++ dynamic vector std object-slicing

g++ -std=gnu++0x main.cpp
In file included from main.cpp:6:0:
CustArray.h: In constructor 'CustArray::CustArray()':
CustArray.h:26:32: error: 'class Info' has no member named 'someInfo'
make: *** [all] Error 1
/*
 * Info.h
 *
 */

#ifndef INFO_H_
#define INFO_H_

class Info
{
    friend class CustArray;
};

#endif /* INFO_H_ */


/*
 * SubInfo.h
 *
 */

#include "Info.h"

class SubInfo : public Info
{

const int someInfo;

public:
    SubInfo(const int someInfo):someInfo(someInfo){}
};

#include <vector>
#include <memory>
#include "Info.h"
#include "SubInfo.h"

template<typename T>
struct ptrModel
{
    typedef std::unique_ptr<T> Type;
};

//Alias shortener.
typedef ptrModel<Info>::Type ptrType;

class CustArray
{

protected:
    std::vector<ptrType> array;

public:
    CustArray()
    {
        ptrType el_init(new SubInfo(1));
        array.push_back(std::move(el_init));
        int someInfo = (*(array[0])).someInfo;
    }

};

/*
 * main.cpp
 *
 */

#include "CustArray.h"
#include <vector>

int main()
{
    CustArray seq;

    return 0;
}

3 个答案:

答案 0 :(得分:4)

std::vector< std::unique_ptr<Base> >就是这样:一个向量充满指针的向量。并且 您无法通过基类指针/引用 访问派生类的内容 - 即使派生类的对象位于这些指针/引用之后。

这与此没什么不同:

SubInfo si(1); 
Info& info = si;
info.someInfo; // won't compile

这并不意味着info后面没有派生类'对象。有。但是 你无法访问它的任何内容,但通过基类接口可以访问 。这是基本的OO。

答案 1 :(得分:1)

不,您有一个指向基类Info的指针,正如编译器所说,它没有名为someInfo的成员。该指针仍指向SubInfo,但您无法通过基类指针访问派生类成员。

如果您确实需要访问该字段,则需要使用dynamic_cast进行向下转换。请务必检查结果以确保演员表有效。

答案 2 :(得分:1)

它说的是真的

error: 'class Info' has no member named 'someInfo'

没有。您无法像尝试一样以多态方式访问子成员。

您需要在类Info中使用虚拟成员函数,例如GetSomeInfo(),它可以是纯虚拟的,也可以在基类中返回一些有趣的东西。然后在子类中,它可以返回someInfo