我到处都围绕着关于SO的这个主题的多个问题以及一些参考资料进行了探讨,但是还没有发现这个问题。
当我的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)的某些delphi继承的功能。
最佳答案
基本和派生的doGetValue定义不同。
基础:
virtual void doGetValue( map<string,string> &ds, const bool include ) const;
inline void doGetValue( map<string,string> &ds ) const { doGetValue(ds, true); };
派生:
virtual void doGetValue( map<string,string> &ds ) const;
在基础上,该功能不是虚拟的。