我已经在这里阅读了几个主题并认为我已经相应地设置了它。我认为问题在于我使用*并且我没有重载<<以某种方式正确设置,即 - 参数定义不正确。问题是编译并成功运行,所以我不知道我在哪里犯了错误。
如果之前已经回答过,我真的很抱歉,但我找不到它。
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <list>
#include <exception>
using namespace std; //Allows us to not prepend std:: to many things.
template<class t>
class HashingTable
{
public:
HashingTable();
HashingTable(int size);
void insert(const char *x);
private:
int x = 0;
vector<list<const char *>> hashedLists;
int currentSize;
int hash(const char * key);
friend std::ostream& operator << (std::ostream & os, const HashingTable<t>);
};
template<class t> std::ostream& operator<< (ostream & os, const HashingTable<t> &ht)
{
const int listSize = ht.size();
for (unsigned int i = 0; i < listSize; i++)
{
list<const char *> searchList = ht[i];
for (std::list<const char *>::const_iterator si = std::next(searchList.begin(), listSizeLimit); si != searchList.end(); ++si) //for each value in hashed list.
cout << *si << " ";
}
return os;
};
template<class t>
int HashingTable<t>::hash(const char * key) {
return key[0] - 'A';
};
template<class t>
HashingTable<t>::HashingTable(int size)
{
hashedLists.resize(size);
};
template<class t>
HashingTable<t>::HashingTable()
{
hashedLists.resize(0);
};
template<class t>
void HashingTable<t>::insert(const char *x) {
//string tempStr(x);
unsigned int hashVal = hash(x);
if (hashedLists.size() < (hashVal + 1)) //if the number of lists in the current vector is less than the resize value then...
hashedLists.resize(hashVal + 1); //resize the hashedLists vector
list<const char *> iList = hashedLists[hashVal];
if (std::find(iList.begin(), iList.end(), x) == iList.end())
{
iList.push_back(x);
hashedLists[hashVal] = iList;
}
currentSize++;
};
int main() /* A sample main program */
{
HashingTable<char*>* mht;
char* Names[25] = { "AB", "AC", "AE", "AZ",
"BA","BM", "BJ", "BZ",
"CA", "CX", "CZ", "CZZ",
"EJ", "EP", "EF", "ES",
"QW", "QE", "QR", "QD",
"SA", "SD", "SF", "SS", "SJ" };
int i;
mht = new HashingTable<char*>(0);
for (i = 0; i < 25; i++)
(*mht).insert(Names[i]);
cout << "Printing the hash table after inserting...." << endl;
cout << *mht;
cout << endl;
return 0;
}
感谢您的任何见解。
答案 0 :(得分:3)
在:
cout << (mht);
不必要的带括号的mht
类型为HashingTable<char*> *
。您提供了operator<<
的重载,需要HashingTable<T> const&
。这些都不一样,所以你的超负荷不被考虑。
你的意思是:
cout << *mht;
答案 1 :(得分:0)
你的朋友声明是无用的,实际上是有害的。它与实际的函数体不匹配,因此它不会帮助它找到它或给私有成员提供额外的访问权限,并且它会在重载解析期间与定义的运算符竞争。
当朋友确实被选中时,编译器会发出对永远不会拥有正文的函数的调用,从而导致未解决的外部错误。
这种类型的友元声明在封闭的命名空间中声明了一系列非模板函数。没有用于定义它们的语法。
删除好友声明。或者将主体内联移动,在这种情况下,您还应该将第二个参数修复为const引用,而不是副本。
当您开始调用已编写的操作员功能体时,您将会收到ht.size()
不存在的其他错误。不要假设这些错误意味着您对运算符的使用是错误的 - 它们实际上意味着您的使用是正确的,并且编译器现在正在尝试解析运算符函数体中的相关名称。