您能解释以下代码的输出吗?我需要做些什么才能调用正确的基类构造函数?
感谢。
#include <vector>
#include <iostream>
template <class CONTAINER> class SequenceComposite {
protected:
CONTAINER m_data;
public:
typedef typename CONTAINER::value_type value_type;
typedef typename CONTAINER::allocator_type allocator_type;
typedef typename CONTAINER::size_type size_type;
explicit SequenceComposite(const allocator_type& alloc = allocator_type()) : m_data(alloc) {
std::cout << std::endl << "SequenceComposite(alloc)" << std::endl;
}
explicit SequenceComposite(size_type n, const value_type& val = value_type(),
const allocator_type& alloc = allocator_type()) : m_data(n, val, alloc) {
std::cout << std::endl << "SequenceComposite(n, val, alloc)" << std::endl;
}
SequenceComposite(const SequenceComposite& x) : m_data(x.m_data) {
std::cout << std::endl << "SequenceComposite(x)" << std::endl;
}
};
template <class DTYPE>
class VectorComposite : public virtual SequenceComposite< std::vector<DTYPE> > {
public:
typedef typename VectorComposite::value_type value_type;
typedef typename VectorComposite::allocator_type allocator_type;
typedef typename VectorComposite::size_type size_type;
explicit VectorComposite(const allocator_type& alloc = allocator_type()) : SequenceComposite< std::vector<DTYPE> >(alloc) {
std::cout << "VectorComposite(alloc)" << std::endl;
}
explicit VectorComposite(size_type n, const value_type& val = value_type(),
const allocator_type& alloc = allocator_type()) : SequenceComposite< std::vector<DTYPE> >(n, val, alloc) {
std::cout << "VectorComposite(n, val, alloc)" << std::endl;
}
VectorComposite(const VectorComposite& x) : SequenceComposite< std::vector<DTYPE> >(x) {
std::cout << "VectorComposite(x)" << std::endl;
}
};
template<typename T> class MyModel : public virtual VectorComposite<T> {
public:
MyModel() {
std::cout << "MyModel()" << std::endl;
};
MyModel(const MyModel<T> &vec) : VectorComposite<T>(vec) {
std::cout << "MyModel(x)" << std::endl;
}
MyModel( size_t n, const T& value= 0) : VectorComposite<T>(n, value) {
std::cout << "MyModel(n, val)" << std::endl;
}
};
int main() {
MyModel<float> c(4, 2.0);
MyModel<float> e(c);
VectorComposite<float> a(3, 2.0);
VectorComposite<float> b(c);
return 0;
}
输出:
SequenceComposite(alloc)
VectorComposite(n, val, alloc)
MyModel(n, val)
SequenceComposite(alloc)
VectorComposite(x)
MyModel(x)
SequenceComposite(n, val, alloc)
VectorComposite(n, val, alloc)
SequenceComposite(x)
VectorComposite(x)
我期待
SequenceComposite(n, val, alloc)
VectorComposite(n, val, alloc)
MyModel(n, val)
SequenceComposite(x)
VectorComposite(x)
MyModel(x)
...
答案 0 :(得分:2)
虚拟基类是从最多派生类型的构造函数初始化的。因此,在前两个示例中,调用SequenceComposite
的默认构造函数。这是带有allocator_type
默认参数的那个。要使用不同的构造函数,请从派生类型最多的初始化列表中调用它。