我一直在跟随CodeBeauty的c++指针教程,在视频中我遇到了一个关于智能指针的问题。
unique_ptr<int>unPtr1=make_unique<int>(25);
cout << unPtr1;
我确实包含了<memory>
,我的语法与所示完全相同,但是每当我试图运行程序时,我都会得到这个错误消息(完整的错误在这里):
pointers.cpp: In function 'int main()':
pointers.cpp:194:22: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'std::unique_ptr<int>')
cout << unPtr1;
~~~~~^~~~~~~~~
这可能是编译器的问题吗?我在VSCode + mingw-64工作。
错误信息告诉您,您正在尝试使用左取std::ostream
,右取std::unique_ptr
的operator<<
,但是编译器找不到这样的操作符。
这样的operator<<
在c++ 20中被添加。
视频中的演示者使用的是Visual Studio。在Visual Studio 2019 v16.9中添加了对c++ 20的支持,并在v16.11中完成。但即使是Visual Studio 2017显然也为std::unique_ptr
定义了operator<<
,至少为c++ 14和c++ 17。假设她正在用现代版本的Visual Studio进行编译,这并不过分,这就解释了为什么这个例子对她来说编译得很好。
因此,请确保您使用的是支持c++ 20标准的mingw-64版本,和您指示它在编译时实际使用该标准。
否则,您可以简单地将cout << unPtr1;
替换为cout << unPtr1.get();
以获得相同的结果。