c++初心者はこちら。現在、int オブジェクトと Student オブジェクトの 2 つの個別のデータ型を処理できる、テンプレート化されたスタックを含むプログラムを作成しようとしています。プログラムのスタック ロジックは問題なく動作しますが、データ型ごとにスタックの一番上に値を出力する方法がわかりません。現在、クラスの '<<' 演算子をオーバーロードする (どちらかはわかりません) か、TopStack() のオーバーロードされた関数を記述する (つまりtemplate <> int Stack<int>::TopStack() const
) という 2 つの考えがあります。後者を実装しましたが、正しくありません。これを達成するための最も効率的な方法を知っている人はいますか? 私はどんな提案にもオープンです。
コードの関連部分を投稿して、私が話していることを確認できるようにします。
template <class DataType>
struct StackNode
{
DataType data; // data can be of any type
StackNode<DataType> *next; // point to the next node
};
template <class DataType>
class Stack
{
private:
StackNode<DataType> *top; // point to the top node of the stack
int maxSize; // maximum stack size
int numNodes; // number of nodes in the stack
public:
Stack(); // constructor, create a stack with size 10
~Stack(); // destructor
bool isEmpty() const { return (top == 0); } // check if the stack is empty
bool isFull() const { return (numNodes == maxSize); } // check if the stack is full
void Push(const DataType &elem); // push a node onto the top of the stack
void Pop(); // pop a node from the top of the stack
int TopStack() const; // return data from the top of the stack
};
struct Students
{
char lastName[20]; // student's last name
char firstName[20]; // student's first name
int IDNumber; // student ID #
Students(); // constructor
void PrintStudent(); // print a student's information
};
void Students::PrintStudent()
{
cout << "\nID# " << this->IDNumber << " - " << this->lastName << ", "
<< this->firstName << endl;
}
// in main() snippet
// if the user asks for top of stack
case 3:
if (!intStack) // I use a boolean to switch the stack being accessed
sstack.TopStack(); // Student stack
else if (intStack)
istack.TopStack(); // Int stack
break;