[英]Why does G++ tell me “Stack” is not declared in this scope?
我創建了以下兩個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;
}
}
和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();
}
然后我嘗試編譯:
[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:
;' before "s" StackTest.cpp:9: error:
s'未在此范圍內聲明
我究竟做錯了什么?
正如您所說,您的Stack
在Stack.cpp
聲明。 您正嘗試在StackTest.cpp
使用它。 您的Stack
未在StackTest.cpp
聲明。 你不能在那里使用它。 這就是編譯器告訴你的。
您必須在所有翻譯單元(.cpp文件)中定義類,您計划在其中使用它們。 此外,您必須在所有這些翻譯單元中以相同方式定義它們。 為了滿足該要求,類定義通常被分成頭文件(.h文件)並包含(使用#include
)到需要它們的每個.cpp文件中。
在您的情況下,您需要創建頭文件Stack.h
,其中包含Stack
類的定義(在本例中為常量定義), Stack.h
包含任何其他內容
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();
};
(頭文件也有利於使用所謂的包含警衛 ,但它現在可以如上所示工作)。
該類定義應該從Stack.cpp
移動到Stack.h
。 相反,您將此.h文件包含在Stack.cpp
。 您的Stack.cpp
將如下開始
#include<iostream>
#include "Stack.h"
using namespace std;
void Stack::init()
{
top = EmptyStack;
}
// and so on...
您以前的Stack.cpp
的其余部分,即成員定義,應保持原樣。
Stack.h
也應該以相同的方式包含在StackTest.cpp
中,所以你的StackTest.cpp
應該以as開頭
#include <iostream>
#include "Stack.h"
using namespace std;
// and so on...
基本上就是這樣。 (而不是提供init
方法,更好的想法是為Stack
類創建一個構造函數。但這是一個不同的故事)。
您需要將class Stack { ...
代碼class Stack { ...
的內容移動到新文件Stack.h中。 然后將以下行添加到StackTest.cpp和Stack.cpp的頂部
#include "Stack.h"
因為StackTest.cpp不知道Stack是什么。
您應該將Stack類定義提取到Stack.h文件中,然后將#include“Stack.h”提取到Stack.cpp和StackTest.cpp中。
或者你可以簡單地將它重命名為Stack.h,盡管最好只有.h文件只暴露類接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.