【问题标题】:C++ Compilation Error. "Stack does not name a type."C++ 编译错误。 “堆栈没有命名类型。”
【发布时间】:2014-02-27 10:35:01
【问题描述】:

我是 C++ 新手,我正在尝试了解堆栈以及类的工作原理,但我似乎根本无法编译我的程序。我不断收到愚蠢的错误,我尝试在网上搜索,但找不到任何有用的东西。如果这个问题很愚蠢,我提前道歉。我是 C++ 新手,我不知道还有什么可以求助的。

谢谢。

每当我尝试编译(make)时,我都会收到此错误:

stacks.cpp:4:1: 错误:‘Stack’没有命名类型 stacks.cpp:7:6: 错误:“堆栈”尚未声明 stacks.cpp:7:18:错误:“字符串” 未在此范围内声明 stacks.cpp:7:18:注意:建议 替代方案:/usr/include/c++/4.6/bits/stringfwd.h:65:33:注意:
'std::string' stacks.cpp:7:27: error: 预期的',' 或';' 在'{'之前 令牌制作:* [stacks.o] 错误 1

堆栈.h

#ifndef _STACK
#define _STACK
// template <class ItemType>;
#include <string>
using namespace std;
class Stack{
    static const int MAX_STACK = 10;
    private:
        string data[MAX_STACK];
        int top; 
    public:
        Stack();
        bool pop(); 
        bool push(string item);
        string peek();
        bool isEmpty();
};
#endif

堆栈.cpp

  #include <cassert>

    Stack::Stack(){
        top = -1;
    }
    bool Stack::Push(string s){
        bool result = false;
        if(top > MAX_STACK - 1){
        ++top;
        data[top] = s;
        result = true;
        }
        return result;
    }
    bool Stack::Pop(){
        bool result = false;
        if(!isEmpty()){
            --top;
            result = true;
        }
        return result;
    }
    string Stack::peek() const{
        assert(!isEmpty());
        return data[top];
    }

Tester.cpp

#include <iostream>
#include <string>
#include <cstdlib>

#include "stacks.h"
int main(){
    Stack test; 
    test.push("Hello");
    test.push("Yes!");
    while(!test.isEmpty()){
        cout << test.peek();
        test.pop();
    }
}

制作文件:

CXX = g++

CXXFLAGS = -Wall -ansi -std=c++0x

TARGET = execute

OBJS = Tester.o stacks.o

$(TARGET) : $(OBJS)
    $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJS)

Tester.o : Tester.cpp
    $(CXX) $(CXXFLAGS) -c -o Tester.o Tester.cpp

stacks.o : stacks.cpp stacks.h
    $(CXX) $(CXXFLAGS) -c -o stacks.o stacks.cpp

.PHONY : clean
clean:
    rm $(OBJS)  

【问题讨论】:

  • 文件是stacks.h 还是stack.h?你也包括stack.cpp中的标题吗?
  • 您需要在stacks.cpp 中包含stacks.h
  • 作为良好实践:全局范围内的 using namespace 指令不应该出现在头文件中,因为它会污染包含头文件的每个 cpp 文件中的全局命名空间。

标签: c++ class c++11


【解决方案1】:

您忘记在Stack.cpp 中包含Stack.h ....您还包含不存在的stacks.hTester.cpp 中包含Stack.h...希望这会有所帮助..

【讨论】:

    【解决方案2】:

    您需要在文件stack.cpp 中包含stack.h

    还有:

    #include "stacks.h"
    

    如果是文件名,则应为 stack.h

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 2021-09-21
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      相关资源
      最近更新 更多