【发布时间】:2012-12-18 23:06:23
【问题描述】:
这是错误:
DummyService.hpp:35:错误:'virtual 的协变返回类型无效 std::vector >& DummyService::list(const std::string&)'
class Bean {
public:
typedef std::string Path;
virtual ~Bean() {};
virtual const Path& getPath() = 0;
virtual const std::string& getName() = 0;
protected:
Bean();
};
class ResourceBean: public Bean {
public:
ResourceBean(const Path& path, const std::string& contents) :
_path(path), _contents(contents) {
}
virtual ~ResourceBean() { }
virtual const Path& getPath();
virtual void setPath(const Path& path);
virtual const std::string& getName();
virtual void setName(const std::string& name);
private:
Path _path;
std::string _name;
};
上面的Bean 类是数据表示,它们被两个不同的层使用。一层使用Bean 接口,只是为了访问数据的getter。 ResourceBean 由数据访问对象 (DAO) 类访问,这些类从数据库中获取数据(例如),并填写 ResourceBean。
DAO 的一个职责是列出给定路径的资源:
class Service {
protected:
/*
* Service object must not be instantiated (derived classes must be instantiated instead). Service is an interface for the generic Service.
*/
Service();
public:
virtual std::vector<Bean*>& list(const Bean::Path& path) = 0;
virtual ~Service();
};
class DummyService: public Service {
public:
DummyService();
~DummyService();
virtual std::vector<ResourceBean*>& list(const ResourceBean::Path& path);
};
我认为问题与std::vector<ResourceBean*> 中的编译器不理解Bean 实际上是ResourceBean 的基类有关。
有什么建议吗?我已经阅读了一些类似的主题,但有些解决方案在我的情况下不起作用。请指出我是否遗漏了什么。提前谢谢你。
【问题讨论】:
-
在继续之前,请注意您的代码不是类型安全的(它是用来编译的)。
std::vector<ResourceBean*>不是std::vector<Bean*>的有效子类型(在一般 LSP 意义上),因为std::vector<ResourceBean*>不支持std::vector<Bean*>所做的所有操作(例如,您可以将任何Bean*放入std::vector<Bean*>,而您只能将ResourceBean*放入std::vector<ResourceBean*>)。 -
感谢您的回复。我试图理解您为什么说“ std::vector
不支持 std::vector 所做的所有操作”。另外,当您说“您可以将任何 Bean* 放入 std::vector 中,而您只能将 ResourceBean* 放入 std::vector ”时,您的意思是您可以放入任何 Bean*(包括派生类的 *)? -
是的。例如,您可以将
FooBean*放入std::vector<Bean*>(其中FooBean是Bean的某个子类),但您不能放入@ 987654342@ 转为std::vector<ResourceBean*>。如果某些代码使用Service::list并希望引用std::vector可以放入FooBean*,那么DummyService::list返回的std::vector<ResourceBean*>将不够用。 -
啊我明白了,谢谢你指出这一点。
标签: c++ pointers interface polymorphism