以下编译良好(在 g++ 8.3.0-6 和 --std=c++17
上),std::stringstream
是一个非静态的类(class)成员:
#include <iostream>
#include <sstream>
class Foo {
public:
std::stringstream ss;
};
int main() {
Foo f;
f.ss << "bar\n";
std::cout << f.ss.str();
}
但以下不是(相同的编译器,相同的选项),其中 stringstream
是 static inline
:
#include <iostream>
#include <sstream>
class Foo {
public:
static inline std::stringstream ss;
};
int main() {
Foo::ss << "bar\n";
std::cout << Foo::ss.str();
}
我的编译器告诉我 std::stringstream
没有默认构造函数,而实际上它应该:
error: no matching function for call to ‘std::__cxx11::basic_stringstream<char>::basic_stringstream()’
static inline std::stringstream ss;
^~
我在这里做错了什么?
最佳答案
这几乎可以肯定是一个编译器错误。编译器在一种情况下知道构造函数重载但在另一种情况下不知道,这有点奇怪,尽管这可能与构造函数是显式
有关。
这确实 compile with 8.3 :
#include <iostream>
#include <sstream>
class Foo {
public:
static inline std::stringstream ss{};
}; //^^
int main() {
Foo::ss << "bar\n";
std::cout << Foo::ss.str();
}
PS:这个答案也得出结论,explicit
是原因 https://stackoverflow.com/a/47782995/4117728 .
关于c++ - 为什么 std::stringstream 在静态内联时不能默认构造?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68831096/