[英]Problem with abstract class inheritance and constructor at C++
[英]Problem with inheritance from abstract class which is also template (c++)
我定義了以下抽象列表 class:
#ifndef LIST_H
#define LIST_H
template <class T>
class List
{
public:
List();
virtual bool isEmpty() const=0;
virtual void Set(int index, T value)=0;
virtual int getSize() const=0;
virtual void add(T value)=0;
virtual T Remove(int index)=0;
virtual ~List();
protected:
int m_size;
private:
};
#endif // LIST_H
然后我定義了一個后繼 DynamicArray:
#ifndef DYNAMICARRAY_H
#define DYNAMICARRAY_H
#include <iostream>
#include "List.h"
#define CAPACITY 15
template<class T>
class DynamicArray : public List<T>
{
public:
//|========================Constructors============================
DynamicArray(): m_size(0), m_capacity(CAPACITY) { //|Default constructor
m_data = new T[CAPACITY];
}
protected:
private:
//|========================Private Fields=========================
int m_capacity;
T* m_data;
};
(這不是完整的 class 定義,當然我實現了析構函數和更多方法,但這與我的問題無關)。
由於某種原因,我收到以下錯誤:
'm_size' was not declared in this scope|
但是 m_size 在基本抽象 class “List”中定義,DynamicArray 繼承自 List。 那么這里出了什么問題呢?
提前致謝。
將構造函數List(int)
添加到初始化m_size
字段的基礎 class 中。
template <class T>
class List
{
public:
List();
List(int _size): m_size(_size) {};
// ....
protected:
int m_size;
};
將此構造函數添加到DynamicArray
的初始化程序中:
template<class T>
class DynamicArray : public List<T>
{
public:
DynamicArray(): List<T>(CAPACITY), m_capacity(CAPACITY) {
m_data = new T[CAPACITY];
}
private:
int m_capacity;
T* m_data;
};
基本初始化程序可以設置const
字段。 DynamicArray(): m_size(0)
試圖做的是:
DynamicArray
List
m_size
不允許第 3 步(如果m_size
是const
怎么辦?)。
在軟件架構方面,類應該負責初始化它們自己的字段。 否則對基礎 class 的內部進行更改將破壞子類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.