【发布时间】:2014-01-01 15:41:45
【问题描述】:
我已经查看了关于 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 继承的功能。
【问题讨论】:
标签: c++ inheritance polymorphism virtual-functions