【发布时间】:2019-04-18 07:24:40
【问题描述】:
这是我的模板类声明:
template <class elemType>
class listType
我有一个这样的构造函数:
listType(const elemType &, const elemType &, const elemType &,
const elemType &, const elemType &){
list[0] = a;
list[1] = b;
list[2] = c;
list[3] = d;
list[4] = e;
}
使用这样的受保护成员变量:
elemType *list;
这是在我的代码中传入 stockType 类型的对象。我从这个模板类 listType 继承了一个名为 stockListType 的类,并尝试创建一个构造函数,它将参数传递给 listType 中已经创建的构造函数:
stockListType :: stockListType(const stockType &a, const
stockType &b, const stockType &c, const stockType &d, const
stockType &e) : listType(a, b, c, d, e) {
}
我不确定我是否了解如何将类模板和构造函数与我继承类的类模板一起使用。
我尝试制作 5 个 stockType 类型的对象(使用文件为成员变量输入它们的信息),然后尝试在我的主代码中将继承类的构造函数与这些对象一起使用:
stockListType object(obj1, obj2, obj3, obj4, obj5);
但是当它尝试运行时我不断收到错误。
编辑: 我得到的错误是 Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
子类头是:
#ifndef stockListTypeHeader_h
#define stockListTypeHeader_h
#include "listType Header.h"
class stockListType : public listType <class stockType>
{
public:
stockListType(const stockType &, const stockType &, const stockType &, const
stockType &, const stockType &);
void sortList();
void swap(stockType&, stockType&);
const void printList();
protected:
stockType *sortIndicesGainLoss;
};
#endif /* stockListTypeHeader_h */
而子类的.cpp文件为:
#include <stdio.h>
#include "stockListTypeHeader.h"
#include "stockType.h"
#include <iostream>
void stockListType:: sortList(){
sortIndicesGainLoss = list;
for(int i =0; i<5; i++){
for(int j =0; j<5-i-1; j++) {
if (sortIndicesGainLoss[j].getStockSymbol() >
sortIndicesGainLoss[j+1].getStockSymbol()){
swap(sortIndicesGainLoss[j], sortIndicesGainLoss[j+1] );
}
}
}
}
void stockListType:: swap(stockType &xp, stockType &yp){
stockType temp = xp;
xp = yp;
yp = temp;
}
void const stockListType:: printList() {
for(int i=0; i<5; i++)
cout << sortIndicesGainLoss[i];
}
stockListType :: stockListType(const stockType &a, const stockType &b, const
stockType &c, const stockType &d, const stockType &e) : listType(a, b, c, d, e)
{
}
编辑 3:
感谢大家帮助我,我发现这是因为我没有初始化列表或我的 sortIndicesGainLoss。
现在我的 sortList 方法出现错误。有人知道为什么吗?
【问题讨论】:
-
"但是当它尝试运行时我一直收到错误。" 什么错误?请edit问题复制并粘贴完整的错误信息。
-
我得到的错误是:线程 1: EXC_BAD_ACCESS (code=1, address=0x0) @Yksisarvinen
-
你有未初始化的指针,它们没有指向有效的内存——像你一样取消引用它们会调用未定义的行为。这与模板或继承无关。此外,您应该更喜欢
std::vector而不是为此的指针 -
“我认为你可以创建一个指针,然后将它的索引分配给你喜欢的对象” - 你从哪里学到的?这是完全错误的,任何像样的课程或教科书都应该解释它
标签: c++ class templates inheritance constructor