C++编码的新手,并试图获得独特的指针。我遇到3个错误
1.cpp|14|error: no match for 'operator<<' 2.cannot bind 'std::basic_ostream<char>' lvalue to std::basic_ostream<char>&&
#include <iostream>
#include <memory>
using std::cout;
using std::cin;
using std::endl;
using std::make_unique;
int main (){
auto ptr = make_unique<int>(4);
cout << "The value of ptr: " << ptr << endl;
cout << "The value of ptr: " << &ptr;
}
最佳答案
ptr
是std::unique_ptr<int>
,并且您没有operator <<(std::ostream&, std::unique_ptr<int>)
的定义,这就是为什么在编译代码时会出错的原因。unique_ptr
只是原始指针的包装。要获取实际的指针(被包装的指针),只需调用get()
,在这种情况下,它将返回一个int*
,您可以在不定义任何其他函数或重载任何运算符的情况下进行打印。要获得ptr
指向的值,只需像普通指针一样取消引用它即可。
#include <iostream>
#include <memory>
int main () {
auto ptr = std::make_unique<int>(4);
std::cout << "The value ptr is pointing: " << *ptr << '\n' // Dereference the pointer
<< "The value of ptr: " << ptr.get() << std::endl; // Get the actual pointer
return 0;
}
关于c++ - C++语法和编译器错误-运算符<<不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553243/