'variable was not declared in this scope' 从派生的 class 的构造函数访问全局变量时
'variable was not declared in this scope' while accessing global variable from a derived class's constructor
我的应用程序代码中有两个 类。我将应用程序分为三个文件。一个头文件 'header.h' ,另一个是 cpp 文件 'header.cpp' ,其中定义了所有使用的函数。最后是我使用 g++ 编译器编译的 main.cpp 文件。以下是所有三个文件的内容。
1) header.h
#include<iostream>
using namespace std;
struct table
{
unsigned int num;
string entry;
};
typedef struct table Table;
Table Randomstuff[]={
{10,"Alphabets"},
{6,"Numbers"},
{8,"Words"},
{6,"Sentences"},
{6,"Phrases"},
{8,"Idioms"}
};
class basics
{
/*data members*/
public:
basics();
void Display(void);
};
class afterbasics: public basics
{
/*Data members*/
public:
afterbasics();
void Display(void);
};
2) header.cpp
basics::basics()
{
for(int i=0;i<6;i++)
{
cout<<Randomstuff[i].entry<<endl;
}
}
3) main.cpp
#include"header.h"
#include"header.cpp"
int main()
{
afterbasics obj;
obj.Display();
}
我使用 g++ main.cpp[RETURN]
编译 main.cpp
文件,但出现以下错误。
In file included from main.cpp:2:0:
header.cpp: In constructor ‘basics::basics()’:
header.cpp:17:9: error: ‘Randomstuff’ was not declared in this scope
cout<<Randomstuff[i].entry<<endl;
谁能告诉我我做错了什么?
此外,我还不熟悉在 Whosebug 上发帖,任何输入都会有所帮助。
我相信header.cpp
需要#include header.h
我的应用程序代码中有两个 类。我将应用程序分为三个文件。一个头文件 'header.h' ,另一个是 cpp 文件 'header.cpp' ,其中定义了所有使用的函数。最后是我使用 g++ 编译器编译的 main.cpp 文件。以下是所有三个文件的内容。
1) header.h
#include<iostream>
using namespace std;
struct table
{
unsigned int num;
string entry;
};
typedef struct table Table;
Table Randomstuff[]={
{10,"Alphabets"},
{6,"Numbers"},
{8,"Words"},
{6,"Sentences"},
{6,"Phrases"},
{8,"Idioms"}
};
class basics
{
/*data members*/
public:
basics();
void Display(void);
};
class afterbasics: public basics
{
/*Data members*/
public:
afterbasics();
void Display(void);
};
2) header.cpp
basics::basics()
{
for(int i=0;i<6;i++)
{
cout<<Randomstuff[i].entry<<endl;
}
}
3) main.cpp
#include"header.h"
#include"header.cpp"
int main()
{
afterbasics obj;
obj.Display();
}
我使用 g++ main.cpp[RETURN]
编译 main.cpp
文件,但出现以下错误。
In file included from main.cpp:2:0:
header.cpp: In constructor ‘basics::basics()’:
header.cpp:17:9: error: ‘Randomstuff’ was not declared in this scope
cout<<Randomstuff[i].entry<<endl;
谁能告诉我我做错了什么?
此外,我还不熟悉在 Whosebug 上发帖,任何输入都会有所帮助。
我相信header.cpp
需要#include header.h