我正在尝试为我的班台Stack制作一个push函数,但是我一直在遇到错误。这是我的代码:(在您询问之前,我知道使用命名空间std是一个坏主意;我们必须现在使用它……)。
标题:
#pragma once
#include <string.h>
using namespace std;
template <class T>
class Stack {
T List[100];
int size;
public:
Stack() : size(0){}
void push(const T &x)
{
strcpy(List[size++], x);
}
const T& pop() {
if (size != 0) return List[size - 1];
}
T print()
{
for (int i = 0; i < size; i++)
cout << List[i] << " ";
}
T reverse();
};
主要
#include <iostream>
#include"Stack.h"
#include <string.h>
using namespace std;
int main()
{
Stack<string> S;
S.push("ana");
S.push("are");
S.push("mere");
S.print();
}
我的错误在strcpy中:无法将参数1从T转换为char *。
答案 0 :(得分:1)
您无需在此处使用strcpy
,只需使用=
来分配输入:
void push(const T &x)
{
List[size++] = x;
}
您的代码中还有其他一些问题。在pop
中,您不会递减size
,并且如果List
为空,也不会返回。一种选择是throw
,如果没有返回值:
const T& pop()
{
if (size != 0)
return List[size--];
throw;
}
此外,您不是从print
返回。但是,似乎没有任何有意义的值要返回,因此可以将其设为void
函数:
void print()
{
for (int i = 0; i < size; i++)
cout << List[i] << " ";
}
这里是demo。