开发者

Is the reason fot the error object slicing?

开发者 https://www.devze.com 2023-01-08 04:42 出处:网络
g++ -std=gnu++0x main.cpp In file included from main.cpp:6:0: CustArray.h: In constructor \'CustArray::CustArray()\':
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;
}


An std::vector< std::unique_ptr<Base> > is just that: a vector filled with pointers to bases. And you cannot access derived class' content through base class pointers/references - even if objects of derived classes are behind those pointers/references.

This is no different from this:

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

That doesn't mean that behind info there isn't a derived class' object. There is. But you cannot access anything of it but what's available through the base class interface. That's basic OO.


No, you have a pointer to the base class Info, which as the compiler says, doesn't have a member named someInfo. That pointer still points to a SubInfo, but you can't access derived class members through a base class pointer.

If you really need access to the field, you would need to use dynamic_cast to downcast. Be sure to check the result to ensure the cast is valid.


What it's saying is true

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

It doesn't. You can not access child members in a polymorphic way like you are attempting.

You will need a virtual member function in the class Info such as GetSomeInfo() which can either be pure virtual or return something interesting in the base class. Then in the child class it can return someInfo

0

精彩评论

暂无评论...
验证码 换一张
取 消