【问题标题】:Is the reason fot the error object slicing?错误对象切片的原因是什么?
【发布时间】:2010-07-22 14:21:22
【问题描述】:
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;
}

【问题讨论】:

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


    【解决方案1】:

    std::vector&lt; std::unique_ptr&lt;Base&gt; &gt; 就是这样:一个填充了指向基址的指针的向量。而且您无法通过基类指针/引用访问派生类的内容 - 即使派生类的对象位于这些指针/引用之后。

    这和这个没有什么不同:

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

    这并不意味着info 后面没有派生类的对象。有。但是您无法访问其中的任何内容,只能通过基类接口获得的内容。这是基本的OO。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        说的是真的

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

        它没有。您不能像您尝试的那样以多态方式访问子成员。

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

        【讨论】:

          猜你喜欢
          • 2021-06-30
          相关资源
          最近更新 更多