【问题标题】:Stack of strings with templates?带有模板的字符串堆栈?
【发布时间】:2020-08-31 04:13:23
【问题描述】:

我正在尝试为我的 Stack 类创建推送功能,但我不断收到错误消息。这是我的代码:(在你问之前,我知道使用命名空间 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: cannot convert argument 1 from T to char * .

【问题讨论】:

  • strcpy 是错误的选择。你为什么选择不使用作业?
  • @molbdnilo 你是对的,谢谢。猜猜我现在很困惑,无法理解我的代码
  • 我不相信“我知道使用命名空间 std 是一个坏主意;我们现在必须使用它......”。你确定吗?如果是这样,请询问为什么
  • @cigien 这是一个测试,所以没有提出任何问题。

标签: c++ class stack


【解决方案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

【讨论】:

    猜你喜欢
    • 2015-02-03
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    相关资源
    最近更新 更多