在以下代码i" m试图实现sean parent"的代码运行时间多态性。我的问题是
1)当我尝试将struct tConcept的方法定义为抽象虚拟的方法时,代码不会编译。错误消息非常精致。有人可以向我解释如何解决此问题
2)当我尝试在主函数上插入以下行并尝试运行摘要i·m获取段故障错误。我该如何修复。
//document.emplace_back(document);
谢谢
sabetay
i" m使用以下在线C 编译器。
https://wandbox.org/
#include <iostream>
using namespace std;
#include <vector>
#include <memory>
#include <cstdio>
#include <cassert>
#include <functional>
#include <algorithm> // std::reverse
template<typename T>
void draw(ostream& os, const T& Entry) {
os << Entry << endl;
}
class TObject {
public :
template<typename T>
TObject(T Entry) : Self(make_unique<TModel<T>>(move(Entry))) {}
friend void draw(ostream& os, const TObject& Entry) {
Entry.Self->ModelDraw(os);
}
TObject(const TObject& Entry) : Self(Entry.Self->Copy()) {}
TObject& operator=(TObject& Entry) { return *this = TObject(Entry); }
TObject(TObject&& Entry) noexcept = default;
TObject& operator=(TObject&& Entry) noexcept = default;
private :
struct TConcept {
virtual ~TConcept() = default;
virtual void ModelDraw(ostream& os) const {} // Must be abstract function
virtual unique_ptr<TConcept> Copy() const {} // Must be abstract function
};
template<typename T>
struct TModel final : TConcept {
T Data;
TModel(T Entry) : Data(move(Entry)) { }
void ModelDraw(ostream& os) const override {
draw(os, Data);
}
unique_ptr<TConcept> Copy() { return make_unique<TConcept>(*this); }
};
unique_ptr<TConcept > Self;
};
using TDocument = vector<TObject>;
void draw(ostream& os, const TDocument& vDoc) {
os << " Document Start" << endl;
for(auto& Entry : vDoc)
draw(os, Entry);
os << " Document End " << endl;
}
int main() {
TDocument Document;
Document.reserve(5);
Document.emplace_back(0);
Document.emplace_back(1);
Document.emplace_back(" Hello World ");
Document.emplace_back(Document); // This line is giving Segment fault why
reverse(Document.begin(), Document.end());
draw(cout,Document);
return 0;
}
1)TModel
中的Copy()
函数与基类中的Copy() const
不同。因此,它不是替代的,使得派生的类也抽象。
2)我不知道您打算做什么Document.emplace_back(Document);
。对我来说,看起来正试图将Document
插入自身。
如果没有其他的话,
Document
存储类型TObject
的元素,而不是类型TDocument
的元素,那么这是行不通的。
进一步看,Document
将持有 Pointers的对象存储到其他对象(嵌套类中很隐藏)。因此,它可能可以容纳包裹的指针。
Document.emplace_back(Document);
的主要问题是覆盖的Copy()
功能试图进行return make_unique<TConcept>(*this);
。但是,make_unique<TConcept>
将尝试执行new TConcept(parameters)
,当TConcept
是抽象时不起作用。
我可以通过将TModel::Copy
函数修改为这个令人讨厌的作品来编译和运行的代码:
unique_ptr<TConcept> Copy() const override
{ return unique_ptr<TConcept>(new TModel(*this)); }
现在它是否有用,我仍然无法分辨。: - )