所以我想做的是编写一个以模板类作为其数据成员的类。这是我作业的一部分。
到目前为止,这就是我所拥有的:
letter_frequencies.h
#include "ltr_freq_pair.h"
#include "darray.h"
class letter_frequencies
{
private:
darray<letterFrequencyStruct> array;
public:
letter_frequencies();
void outputFrequencies();
};
letter_frequencies.cpp
#include <iostream>
#include "letter_frequencies.h"
letter_frequencies::letter_frequencies()
{}
void letter_frequencies::outputFrequencies()
{
for(int index = 0; index < 26; index ++)
{
std::cout << "\n" << array[index].letter;
std::cout << " " << array[index].frequency;
}
}
一切都能编译,但是一旦我运行程序,它就会出现此错误:
a.out: darray.cpp:44: T& darray<T>::operator[](unsigned int) [with T = letterFrequencyStruct]: Assertion 'index < used' failed.Abort (core dumped)
我要用于此类的代码段是:
//Check if Class Works
letter_frequencies array;
array.outputFrequencies();
现在,darray可以正常工作,并且程序可以完全满足我的需要,但是其中一项要求是拥有一个名为letter_frequency的类,并带有一个数据成员
darray<structTypename> name
,这就是为什么我在这里大惊小怪第一名。另外,如何使该类为darray调用显式构造函数?我想将大小设置为26。
darray.h
#ifndef DARRAY_H
#define DARRAY_H
#include <iostream>
template <typename T>
class darray
{
public:
//Constructors
darray();
darray(const darray&);
explicit darray(unsigned);
//Destructor
~darray();
//Constant Members
unsigned size() const {return used;}
unsigned capacity() const {return cap;}
//Modification Members
T& operator [] (unsigned);
void pop_back();
void push_back(const T&);
const T* find(const T&) const;
void resize(unsigned);
//Operators
T& operator = (const darray&);
bool operator == (const darray&) const;
//Friends
template <typename X>
friend std::ostream& operator << (std::ostream& output, const darray<X>& array);
private:
T* arr;
unsigned used, cap;
};
template <typename X>
std::ostream& operator << (std::ostream& output, const darray<X>& array)
{
for(int index = 0; index < array.size; index++)
{
output << index << array[index];
}
return output;
}
#include "darray.cpp"
#endif
最佳答案
如前所述,您必须像这样创建letter_frequencies
构造函数:
letter_frequencies::letter_frequencies() : array(26) {
}
(因此,您可以使用必要数量的元素初始化数组)。
但是:我认为当
array
更好时,您不应该自己制作自己的std::vector
...