繁体   English   中英

实施模板类接口

[英]Implementing a template class 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;
};

感谢您在解释我的逻辑失败的地方以及有关如何正确执行任务的任何提示方面的帮助。 谢谢!

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

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

2)但是,在您的小示例中,无需使用“ new”创建sorted1。

sorted<string> sorted1;

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

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

其次,在您的sortedInterface模板中,已将成员虚拟化,该成员仍需要一个定义,但不提供定义。 您可以将成员函数标记为= 0; 为了使它们全部都是纯虚拟的 ,这意味着继承您sortedInterface的类将必须实现这些成员。

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

最后,如果您到处都在使用裸new() ,请看一下智能指针

我注意到整个实现中存在以下其他异常情况:

  • 接口应该是不可实例化的,但是在您的情况下可以实例化(因为甚至没有单个纯接口
    您所谓的界面中的虚拟函数)标准规则是
    将接口中的所有功能设为纯虚拟(= 0)
  • class Sorted不继承于所谓的sortedInterface接口
  • 您尚未在class Sorted定义构造函数的所有版本
  • 如果您希望多态性有效(Interface to Concrete),则
    需要在接口和接口中都具有虚拟类析构函数
    具体课

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM