0
我环顾了这个主题上的多个问题,以及几个参考,并没有看到这个问题出现在任何地方。基类功能不调用派生类功能
当我的Derived
实例调用Base::GetValue()
(它调用virtual
doGetValue()
,在Derived
和Base
定义),Base::doGetValue()
被调用,而不是Derived::doGetValue()
。为什么是这样,我需要做什么不同?
是因为Derived::doGetValue()
是private
而不是protected
?在我看来,这似乎是最有可能的解释,但我还没有看到明确指出我迄今看到的任何地方。
Here是我的coliru代码。
下面是我的代码:
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <memory>
using namespace std;
class Base
{
private:
virtual string doGetname() const { return "Base"; };
protected:
virtual void doGetValue(map<string,string> &ds, const bool include) const;
inline void doGetValue(map<string,string> &ds) const { doGetValue(ds, true); };
public:
string GetValue() const;
string GetName() const { return doGetname(); };
};
class Derived : public Base
{
private:
virtual void doGetValue(map<string,string> &ds) const;
virtual string doGetname() const { return "Derived"; };
};
struct generate_value_from_map : std::unary_function<void, void>
{
generate_value_from_map(string *_val, const string assignment = " "):val(_val)
{
count = 0;
insert = (*_val);
first = "(";
second = ") "+assignment+" (";
}
void operator() (pair<const string,string> &i)
{
first += (count > 0 ? "," : "") + i.first;
second += (count > 0 ? "," : "") + i.second;
(*val) = insert + first + second + ")";
++count;
}
private:
int count;
string *val;
string insert;
string first;
string second;
};
string Base::GetValue() const
{
string ret_val = "name is: " + GetName() + " \n";
map<string,string> ret_map;
this->doGetValue(ret_map);
for_each(ret_map.begin(), ret_map.end(), generate_value_from_map(&ret_val));
return ret_val;
}
void Base::doGetValue(map<string,string> &ds, const bool include) const
{
//base implementation
//fills ds with values from Base
ds["type"] = "Base";
ds["id"] = "Id";
}
void Derived::doGetValue(map<string,string> &ds) const
{
Base::doGetValue(ds);
//derived implementation
//fills ds with values from Derived
ds["type"] = "Derived";
ds["name"] = "Name";
}
int main()
{
shared_ptr<Derived> obj (new Derived());
string val = obj->GetValue();
cout << val;
//do stuff with val
}
我想包括我的问题的所有细节,但不包括我的一些编译器(RAD Studio的XE4)的德尔福继承的功能。
所以我需要重载的'doGetValue(...)'是'虚拟内联'而不是'内联'? – caps
内联在虚拟功能中没有意义。你可以放弃它。它在你的例子中必须是虚拟的。 – egur
谢谢,这照顾它。 – caps