[英]Replace default copy constructor with copy constructor for base class (c++)
I have an abstract class list: 我有一个抽象的类列表:
template <class V>
class List {
public:
void toArray(void*) const = 0;
// other methods
};
And I have an inherited class arraylist: 我有一个继承的类arraylist:
template <class V>
class ArrayList:
public List<V>
{
public:
ArrayList(const List<V>&);
void toArray(void*) const;
private:
ArrayList(const ArrayList&); //Remove default copy ctor
// other methods and functions
};
When calling ArrayList(const ArrayList&)
I would like to use the constructor for ArrayList(const List&)
. 当调用
ArrayList(const ArrayList&)
我想使用ArrayList(const List&)
的构造ArrayList(const List&)
。
LinkedList<int> link; // also inherited from list
// populate list
ArrayList<int> lst = link; // works fine
ArrayList<int> newList = lst; // error ctor is private
I would not like to rewrite the code in ArrayList(const List&)
for ArrayList(const ArrayList&)
because they both use the same toArray(void*)
method declared in List
. 我不想为
ArrayList(const ArrayList&)
重写ArrayList(const List&)
的代码,因为它们都使用List
声明的相同toArray(void*)
方法。 How do I do this? 我该怎么做呢? I would also like to avoid calling the default ctor of
ArrayList
because it allocates a minimum sized array of 8 values. 我还想避免调用
ArrayList
的默认ctor,因为它分配了8个值的最小大小的数组。
template <class V>
class ArrayList: public List<V>
{
public:
ArrayList(const List<V>&);
// use delegating constructor (C++11 feature)
ArrayList(const ArrayList& val) : ArrayList( static_cast<const List<V>&>(val) ) {}
void toArray(void*) const;
private:
};
If your compiler does not support C++11: 如果您的编译器不支持C ++ 11:
template <class V>
class ArrayList: public List<V>
{
public:
ArrayList(const List<V>& val) { construct(val;) }
ArrayList(const ArrayList& val) { construct(val;) }
void toArray(void*) const;
private:
void construct(const List<V>&);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.