【发布时间】: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 文件中的全局命名空间。