实现模板类接口

时间:2014-02-02 22:03:59

标签: c++ class templates interface

我对c ++比较陌生,并且很快就会让我的主程序实例化我的课程。我已经习惯了java所以我不确定我是否正在混合这两种语言,因为我试图这样做,这是我的问题,或者我只是不理解这个概念。

我的程序的对象:该程序的目标是从一个接口创建一个模板类,该接口将创建一个排序数组,您可以在保持排序的同时添加和删除项目。

注意: 请帮我实际理解这个过程,只是告诉我使用的确切代码,因为我真的想了解下次我做错了什么

第1步:我创建了我的排序界面:

sortedInterface.h
#ifndef _SORTED_INTERFACE
#define _SORTED_INTERFACE

#include <vector>
using namespace std;

template<class ListItemType>
class sortedInterface
{
public:
    virtual bool sortedIsEmpty();
    virtual int sortedGetLength();
    virtual bool sortedInsert(ListItemType newItem);
    virtual bool sortedRemove(ListItemType anItem);
    virtual bool sortedRetrieve(int index, ListItemType dataItem);
    virtual int locatePosition(ListItemType anItem);

}; // end SortedInterface
#endif

然后我使用接口创建sorted.h文件:

sorted.h
#include "sortedInterface.h"
#include <iostream>
#ifndef SORTED_H
#define SORTED_H

using namespace std;

template<class ListItemType>
class sorted
{
    public:
        sorted();
        sorted(int i);
        bool sortedIsEmpty();
        int sortedGetLength();
        bool sortedInsert(ListItemType newItem);
        bool sortedRemove(ListItemType anItem);
        bool sortedRetrieve(int index, ListItemType dataItem);
        int locatePosition(ListItemType anItem);
    protected:
    private:
        const int DEFAULT_BAG_SIZE = 10;
        ListItemType items[];
        int itemCount;
        int maxItems;
   };

#endif // SORTED_H

最后我创建了sorted.cpp(我现在只包含构造函数,因为我甚至无法正常工作)

#include "sorted.h"

#include <iostream>

using namespace std;


template<class ListItemType>
sorted<ListItemType>::sorted()
{
    itemCount = 0;
    items[DEFAULT_BAG_SIZE];
    maxItems = DEFAULT_BAG_SIZE;
}

我的主要计划:

#include "sortedInterface.h"
#include "sorted.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
    sorted<string> sorted1 = new sorted();

    return 0;
};

在解释我的逻辑失败的地方以及如何正确执行我的任务的任何提示时,我们都非常感激。谢谢!

3 个答案:

答案 0 :(得分:1)

1)运算符“new”返回指针,而不是对象。

sorted<string>* sorted1 = new sorted<string>();

2)但是,在你的小例子中,没有必要使用“new”创建sorted1。

sorted<string> sorted1;

一句忠告 - Java不是C ++。你犯了许多第一次Java程序员在编写C ++代码时犯的两个错误,即1)相信创建一个对象,你必须使用“new”,2),“new”返回一个引用。

答案 1 :(得分:1)

您的界面/实施存在一些问题。类模板通常完全在声明它的标题中实现;这是因为编译器会为模板使用的每种类型创建一个全新的类型。

其次,在您的sortedInterface模板中,您已将成员设为虚拟,但仍需要定义,但您不提供定义。您可以使用= 0;标记您的成员函数,使其全部pure virtual,这意味着继承sortedInterface的类必须实现这些成员。

第三,正如PaulMcKenzie指出的那样,operator new()返回一个指向堆分配对象的指针,但是你期望得到一个值类型。

最后,如果您到处使用裸new(),请查看smart pointers

答案 2 :(得分:0)

我注意到整个实现中存在以下额外异常:

  • 接口是应该是不可实例化的东西,但它是 在你的情况下可以实例化(因为甚至没有一个纯粹的 你所谓的界面中的虚函数)标准规则是为了 使界面中的所有函数都是纯虚拟(= 0)
  • import sys print(sys.stdin.readlines()) # echo "hello" | python preprocess_image.py # => ['hello\n'] 不会继承所谓的界面 class Sorted
  • 您尚未在sortedInterface
  • 中定义构造函数的所有版本
  • 如果你想要多态性工作(接口到混凝土),你就是 需要在接口和
    中都有虚拟类析构函数 具体课程