cch*_*ion 0 c++ polymorphism virtual inheritance
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
class Helper
{
public:
Helper() { init(); }
virtual void print() {
int nSize = m_vItems.size();
std::cout << "Size : " << nSize << std::endl;
std::cout << "Items: " << std::endl;
for(int i=0; i<nSize; i++) {
std::cout << m_vItems[i] << std::endl;
}
}
protected:
virtual void init() { m_vItems.push_back("A"); }
std::vector<std::string> m_vItems;
};
class ItemsHelper : public Helper
{
public:
ItemsHelper() { }
protected:
virtual void init() {
Helper::init();
m_vItems.push_back("B");
}
};
int _tmain(int argc, _TCHAR* argv[]) {
ItemsHelper h;
h.print();
}
Run Code Online (Sandbox Code Playgroud)
这个输出是向量的大小是1.我期望大小为2,因为在ItemsHelper :: init函数中我调用了基类Helper::init()
函数,然后我向向量添加了第二个项.问题是,ItemsHelper :: init没有被调用,而是调用基类init函数.
我希望调用ItemsHelper :: init函数,我可以通过调用ItemsHelper ctor中的init函数而不是基类来实现. 但是,问题是,是否有更好的方法来实现它并仍然保持对基类中的init()的调用?因为如果我想创建一个Helper对象而不是ItemsHelper,那么init函数永远不会被调用.
顺便说一下,这是我在一个更大的对象中看到的问题的简化版本,我只是以这些对象为例.
在基类构造函数中,尚未构造派生类,因此派生类上的overriden函数尚不可用.在这个地方有一个FAQ条目......我找不到.
最简单的解决方案是将.push_back("A")
部分init
放入Helper
构造函数中,然后.push_back("B")
放入ItemsHelper
构造函数中.这似乎做了你想要做的事情,并削减了不必要的init
虚拟功能.