向向量添加共享指针时出错

时间:2015-10-15 17:30:09

标签: c++ c++11 shared-ptr

抽象基类:

#ifndef BUILDINGORG_H
#define BUILDINGORG_H
#include <iostream>
#include <memory> 
#include <vector>

class BuildingOrg
{

public:
   BuildingOrg(int _id);
   virtual int addBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg,
                                    std::string _type) const;
   virtual void removeBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg);
   virtual void getInfo()=0;
private:
   int id;
   std::string type;
};

#endif // BUILDINGORG_H

具体子类:

#ifndef BUILDINGCOMPONENT_H
#define BUILDINGCOMPONENT_H
#include "buildingorg.h"

class BuildingComponent : public BuildingOrg
{
public:
    BuildingComponent(int _id);
    int addBuildingComponent(std::shared_ptr<BuildingOrg> _buildingOrg,
                             std::string _type) const override;
    void removeBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg)
                                                        override;
    void getInfo() override;
private:
    std::vector<std::shared_ptr<BuildingOrg>> building_Org;
};

#endif // BUILDINGCOMPONENT_H

子类的实现:

#include "buildingcomponent.h"

BuildingComponent::BuildingComponent(int _id):
BuildingOrg(_id)
{
}

int BuildingComponent::addBuildingComponent(std::shared_ptr<BuildingOrg> _buildingOrg, std::string _type) const
{
    building_Org.push_back(_buildingOrg);// I am having error here
    return 1;
}

void BuildingComponent::removeBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg)
{

}

void BuildingComponent::getInfo()
{

}

当我尝试将共享指针放在我的Vector中时,我得到了这个令人讨厌的错误; 我真的不知道为什么我会收到错误:

cpp:10: error: passing 'const std::vector<std::shared_ptr<BuildingOrg> >' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::shared_ptr<BuildingOrg>; _Alloc = std::allocator<std::shared_ptr<BuildingOrg> >; std::vector<_Tp, _Alloc>::value_type = std::shared_ptr<BuildingOrg>]' discards qualifiers [-fpermissive]
        building_Org.push_back(_buildingOrg);

我不明白它在说什么。

3 个答案:

答案 0 :(得分:4)

const中的int addBuildingComponent(std::shared_ptr<BuildingOrg> _buildingOrg, std::string _type) const override;addBuildingComponent不会更改BuildingComponent的承诺。但是,它尝试使用building_Org ...

修改成员变量push_back()

const中移除addBuildingComponent()应该可以解决错误。

错误消息的discards qualifiers部分是指与成员函数的const限定符冲突。

与C ++模板相关的错误消息一开始可能很难解析,但通过练习确实更容易: - )

答案 1 :(得分:1)

您将BuildingComponent :: addBuildingComponent方法定义为const(即它不会更改成员变量),但您将传入的值添加到成员列表中(即更改成员变量)。

答案 2 :(得分:0)

  1. addBuildingComponent()是一种const方法。在其范围内,*thisconst,因此this->building_Orgconst

  2. std::vector::push_back()是一种非const方法。因此,无法在向量为const

  3. 的上下文中调用它