gpt4 book ai didi

c++ - 如何修复模板 BST 类的对象初始化?

转载 作者:行者123 更新时间:2023-11-30 03:15:16 25 4
gpt4 key购买 nike

这个问题出现在我的 main.cpp 中:

using namespace std;

#include <iostream>

#include "BST.h"
#include "Packet.h"

int main()
{
BST test; // It occurs on this line!
Packet one(1, "testPacket", 1, 1);

system("Pause");
}

该行的错误是:

argument list for class template "BST" is missing

我不知道怎么解决。我只想初始化 BST。我该如何解决这个错误?我对模板不是很有经验。请帮忙。 我的首要任务是立即解决这个明显的问题。我能得到帮助吗?

供引用:

BST.h:

#ifndef BST_H
#define BST_H

using namespace std;

template <typename T>
class Node {
public:
Node() : rlink(nullptr), llink(nullptr) {}
~Node() {}
private:
T data;
Node *rlink, *llink;

};

template <typename T>
class BST {
public:
BST();
void insert(T data);
private:
Node * root;
};

#endif

BST.cpp

#include "BST.h"

template <typename T>
BST<T>::BST() : root(nullptr) {}

template <typename T>
void BST<T>::insert(T data) {
if (root != nullptr) {

}
else {
cout << "NPTR" << endl;
}
}

Packet.h

#ifndef PACKET_H
#define PACKET_H

#include <string>

using namespace std;

class Packet {
public:
Packet(int partId, string description, double price, int partCount) :
partId(partId), description(description), price(price), partCount(partCount) {}
int getPartId() const { return partId; }
string getDescription() const { return description; }
double getPrice() const { return price; }
int getPartCount() const { return partCount; }
private:
int partId;
string description;
double price;
int partCount;
};

#endif

最佳答案

有两个问题。

首先是 Node 需要知道 T 是什么类型,所以当你使用 Node 时需要告诉它,像这样:

template <typename T>
class BST {
public:
BST();
void insert(T data);
private:
Node<T> * root;
};

其次,BST 在您尝试使用它时需要知道它自己的类型 T 是什么,因此您需要这样做:

BST<int> test; // Or whatever you are searching for in your tree. Doesn't have to be an int

附言现在就开始吧,you're probably going to need to implement BST in the header file .否则可能会导致链接器问题。


附言我一直在阅读您对原始帖子的评论,以及您实际上可能需要的是:

BST<Packet> test; // Since you are searching for packets.

关于c++ - 如何修复模板 BST 类的对象初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57192586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com