我定義了以下抽象 List 類:
#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;
};
(這不是完整的類定義,當然我實作了一個解構式和更多方法,但這與我的問題無關)。
由于某種原因,我收到以下錯誤:
'm_size' was not declared in this scope|
但是 m_size 是在基礎抽象類“List”中定義的,DynamicArray 繼承自 List。那么這里出了什么問題呢?
提前致謝。
uj5u.com熱心網友回復:
將建構式添加到初始化欄位List(int)的基類。m_size
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?)。
在軟體架構方面,類應該負責初始化它們自己的欄位。否則對基類的內部進行更改會破壞子類。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/421222.html
標籤:
上一篇:C 類不輸出正確的資料?
