为什么G ++告诉我"Stack"未在此范围内声明?

Mit*_*rax 2 c++

我创建了以下两个C++文件:

Stack.cpp

#include<iostream>

using namespace std;

const int MaxStack = 10000;
const char EmptyFlag = '\0';

class Stack {

    char items[MaxStack];
    int top;
public:
    enum { FullStack = MaxStack, EmptyStack = -1 };
    enum { False = 0, True = 1};
    // methods
    void init();
    void push(char);
    char pop();
    int empty();
    int full();
    void dump_stack();
};

void Stack::init()
{
    top = EmptyStack;
}

void Stack::push(char c)
{
    if (full())
        return;

    items[++top] = c;
}

char Stack::pop()
{
    if (empty())
        return EmptyFlag;
    else
        return items[top--];
}

int Stack::full()
{
    if (top + 1 == FullStack)
    {
        cerr << "Stack full at " << MaxStack << endl;
        return true;
    }
    else
        return false;
}

int Stack::empty()
{
    if (top == EmptyStack)
    {
        cerr << "Stack Empty" << endl;
        return True;
    }
    else
        return False;
}

void Stack::dump_stack()
{
    for (int i = top; i >= 0; i--)
    {
        cout << items[i] << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

和StackTest.cpp

#include <iostream>

using namespace std;

int main()
{

Stack s;
s.init();

s.push('a');
s.push('b');
s.push('c');

cout << s.pop();
cout << s.pop();
cout << s.pop();

}
Run Code Online (Sandbox Code Playgroud)

然后我尝试编译:

[USER @ localhost cs3110] $ g ++ StackTest.cpp Stack.cpp StackTest.cpp:函数int main()': StackTest.cpp:8: error:Stack'未在此范围内声明StackTest.cpp:8:错误:预期;' before "s" StackTest.cpp:9: error:s'未在此范围内声明

我究竟做错了什么?

AnT*_*AnT 8

正如你所说,你Stack被宣布进入Stack.cpp.你正试图用它StackTest.cpp.你Stack不是在声明StackTest.cpp.你不能在那里使用它.这就是编译器告诉你的.

您必须在所有翻译单元(.cpp文件)中定义类,您计划在其中使用它们.此外,您必须在所有这些翻译单元中以相同方式定义它们.为了满足该要求,类定义通常被分成头文件(.h文件)并包含(使用#include)到需要它们的每个.cpp文件中.

在您的情况下,您需要创建头文件Stack.h,包含Stack类的定义(在本例中为常量定义),而不包含任何其他内容

const int MaxStack = 10000; 
const char EmptyFlag = '\0'; 

class Stack { 

    char items[MaxStack]; 
    int top; 
public: 
    enum { FullStack = MaxStack, EmptyStack = -1 }; 
    enum { False = 0, True = 1}; 
    // methods 
    void init(); 
    void push(char); 
    char pop(); 
    int empty(); 
    int full(); 
    void dump_stack(); 
}; 
Run Code Online (Sandbox Code Playgroud)

(头文件也有利于使用所谓的包含警卫,但它现在可以如上所示工作).

这个类定义应移动Stack.cppStack.h.相反,您将包含此.h文件Stack.cpp.您Stack.cpp将从以下开始

#include<iostream>     

#include "Stack.h"

using namespace std;    

void Stack::init()      
{      
    top = EmptyStack;      
}      

// and so on...
Run Code Online (Sandbox Code Playgroud)

其余的前者Stack.cpp,即成员定义,应保持原样.

Stack.h也应纳入StackTest.cpp,以同样的方式,所以你StackTest.cpp应该开始为

#include <iostream>        

#include "Stack.h"

using namespace std; 

// and so on...
Run Code Online (Sandbox Code Playgroud)

基本上就是这样.(而不是提供一种init方法,更好的想法是为类创建一个构造函数Stack.但这是一个不同的故事).