请帮助我了解此错误的来源 - 我无法判断它是代码还是 IDE 的设置。尽管“超出范围”的问题很常见,但我已经搜索了答案,但没有找到有帮助的东西。
我正在 SoloLearn 上在线学习 C++ 类(class)。根据他们的建议,我已经在 Linux 中下载并设置了 Codeblocks,这样我就可以通过编写代码并在 IDE 中编译它来学习类(class),而不是简单地通过他们的浏览器窗口在线学习。到目前为止一切都很好;0/
所以我正在学习关于“组合”的类(class)并且(再次遵循他们的建议)分解了他们的代码并创建了单独的文件来定义构造函数/类。然而,尽管我相信我做的一切都是正确的,但我还是不断收到这个“超出范围”的错误。
这是他们的代码,写在一页上。如果我将其作为单个文件复制并粘贴到 IDE 中,它会成功编译,并且我选择的终端窗口会弹出预期的输出:
#include <iostream>
using namespace std;
class Birthday {
public:
Birthday(int m, int d, int y)
: month(m), day(d), year(y)
{ }
void printDate()
{
cout<<month<<"/"<<day <<"/"<<year<<endl;
}
private:
int month;
int day;
int year;
};
class Person {
public:
Person(string n, Birthday b)
: name(n), bd(b)
{ }
void printInfo()
{
cout << name << endl;
bd.printDate();
}
private:
string name;
Birthday bd;
};
int main() {
Birthday bd(2, 21, 1985);
Person p("David", bd);
p.printInfo();
}
我现在正在做的是将第一个构造函数定义删除到单独的 .h
和 .cpp
文件中,如下所示:
#ifndef BIRTHDAY_H
#define BIRTHDAY_H
class Birthday
{
public:
Birthday(int m, int d, int y);
void printDate();
private:
int month;
int day;
int year;
};
#endif // BIRTHDAY_H
和
#include "Birthday.h"
using namespace std;
Birthday::Birthday(int m, int d, int y)
: month(m), day(d), year(y)
{ }
void printDate()
{
cout<<month<<"/"<<day <<"/"<<year<<endl;
}
无论我做什么,我都会清理并重新运行项目文件。我已经删除并重新创建了它们。我已经重启了。但每次我尝试构建时,我都会得到以下信息:
- 错误:cout 未在此范围内声明
- 错误:月份未在此范围内声明
- 错误:日期未在此范围内声明
- 错误:年份未在此范围内声明。
如果代码根本无法工作,我会更仔细地检查我的工具,但为什么将它复制到单独的文件中会给我这个错误?
最佳答案
您需要在 Birthday.cpp 或 Birthday.h 中包含 iostream
。其次,printDate
的定义需要限定在类的范围内:Birthday::printdate
。
关于c++ - 尝试解决 "out of scope"编译错误 : CodeBlocks, Linux Fedora,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41913518/