gpt4 book ai didi

c++ - 在 main() 之外调用方法是否错误

转载 作者:太空狗 更新时间:2023-10-29 23:36:24 25 4
gpt4 key购买 nike

我想知道是否有人可以解释以下错误的含义:

代码

    #include "sstream"

std::stringstream h;

h.str(""); //clearing the stringstream object

int main()

错误

kial.cpp:5:1: error: ‘h’ does not name a type h.str("");

还有为什么尝试访问 main() 之外的方法是错误的?

最佳答案

好的,所以每个人都带着一个简单的声明来到这里,说你做不到。不相信任何人。事实上,你可以。但不像你尝试过那样做。通常,你不能在其他函数之外有函数调用之类的语句。第一个被调用的函数总是 main。但是,C++ 有 RAII和全局对象。因此,上述规则只有一个异常(exception)——全局对象的构造和销毁。通过雇用 RAII并声明一些全局对象,你可以调用它的构造函数,然后从那里做剩下的事情。因此,例如,您可以这样解决问题:

#include <sstream>
#include <iostream> // just for std::cout and std::endl.

std::stringstream h;

struct MyStruct {
MyStruct() {
h.str(""); //clearing the stringstream object
std::cout << "`h` string stream is cleared now!" << std::endl;
}
};

MyStruct mystruct;

int main()
{
std::cout << "I am called AFTER MyStruct's constructor" << std::endl;
}

编译运行:

$ g++ -Wall -pedantic -std=c++98 ./test.cc  && ./test
`h` string stream is cleared now!
I am called AFTER MyStruct's constructor

希望对您有所帮助。祝你好运!

关于c++ - 在 main() 之外调用方法是否错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16328890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com