C++ 没有命名代码块中的类型错误

C++ does not name a type error in Codeblocks

我正在尝试在代码块中编译这个简单的 C++ 程序:

#include <string>
#include <fstream>
#include <streambuf>
#include <sstream>

std::ifstream t("C:/Windows/System32/drivers/etc/hosts-backup.txt");
std::stringstream buffer;
buffer << t.rdbuf();

我得到这个错误:

||=== Build: Debug in hostapp2 (compiler: GNU GCC Compiler) ===|

C:\Users\Flights Trainer\Desktop\hostapp2\main.cpp|7|error: 'buffer' does not name a type|

||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

我整晚都在谷歌搜索“没有命名类型”,我发现的所有内容都指向在声明之前使用 class,但我不明白我在做什么。

我做错了什么?

你不能在 C++ 的文件范围内放置任意语句,你需要将它们放在一个函数中。

#include <string>
#include <fstream>
#include <streambuf>
#include <sstream>

int main () {
    //These are now local variables
    std::ifstream t("C:/Windows/System32/drivers/etc/hosts-backup.txt");
    std::stringstream buffer;

    //We can write expression statements because we're in a function
    buffer << t.rdbuf();
}

如果你的代码和你写的一样,那你玩得很开心。由于它不是函数中的代码,您基本上是在声明变量、类 和函数——这就是您在全局范围内可以做的所有事情。

//Global variable with type ifstream, named t
std::ifstream t("C:/Windows/System32/drivers/etc/hosts-backup.txt");
//Global variable with type stringstream, named buffer
std::stringstream buffer;
//Global variable with type buffer... Em what?!
buffer << t.rdbuf();

这就是您遇到的错误。在 C++ 中,您可以编写仅在函数中执行的语句。