【发布时间】:2016-02-19 16:46:03
【问题描述】:
该程序包含一个名为 collection 的类,其中包含虚拟 void 函数。我在 main 中制作的动态数组应该能够从文件中接受任意数量的整数,每一行都有一个文件编号。它允许用户指定他们想要读取的文件名。这是头文件:
#ifndef Collection_H
#define Collection_H
class collection{
public:
collection(); //constructor
virtual void add(int value) = 0; //adds the value to the array
virtual void remove(int index) = 0; //removes and item from the appropriate index location
virtual void print() = 0; //prints item of the array comma seperated.
virtual int get(int index) = 0; //gets item at a particular index.
virtual int sum() = 0; //gets the sum of the array
virtual int size() = 0; //gets the size of the array
};
我对这个程序的第一个问题有点概念性:virtual 实际上做了什么,为什么要使用它以及如何实际实现它?我确实知道,因为您必须创建派生类才能实现虚函数。因此,这是我的派生类头:
// this is the derived collection
#include "Collection.h"
#ifndef derivedcollection_H
#define derivedcollection_H
class derivedcollection: public collection
{
public:
collection(); //constructor (error is at this line)
virtual void add(int value) = 0; //adds the value to the array
virtual void remove(int index) = 0; //removes and item from the appropriate index location
virtual void print() = 0; //prints item of the array comma seperated.
virtual int get(int index) = 0; //gets item at a particular index.
virtual int sum() = 0; //gets the sum of the array
virtual int size() = 0; //gets the size of the array
};
#endif
我的下一个也是最后一个问题更像是一个我不明白的简单错误。对于 collection(); 所在的行在我的派生类派生集合中声明,我收到一条错误消息,指出“缺少显式类型(假定为'int')”。虽然这通常是一个要修复的简单错误,但老实说,为什么它会给我这个错误有点令人困惑。当我在派生类头而不是基类头中声明默认构造函数时,它如何给我这个错误?
【问题讨论】:
-
构造函数与它们所在的类同名。
derivedcollection的构造函数必须调用derivedcollection。
标签: c++ inheritance constructor syntax-error virtual