2016-09-18 102 views
-1

新的C++编码,并试图获得唯一指针的手。我运行到3个错误C++语法和编译器错误 - 操作符不匹配<<

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; 

} 
+1

您需要取消引用'ptr':'COUT << “PTR的价值:” << * PTR << ENDL;' – ildjarn

回答

1

ptrstd::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; 
} 
0

有许多语法错误在此代码,以便下面是正确的程序,你可以尝试:

#include <iostream> 
#include <memory> 
int main() 
{ 


using std::cout; using std::cin; using std::endl; 

using std::make_unique; 

auto ptr = make_unique<int>(4); 

//there is no overload of ostream operator for std::unique_ptr 
//so you can't directly do << ptr 
cout << "The value of ptr: " << *ptr << endl; 
//& will print address not value 
cout << "The Address of ptr: " << &ptr; 


} 
+0

添加解释会更好。 – songyuanyao

+0

'cout <<“ptr的地址:”<< &ptr;'显示'unique_ptr'的地址,而不是'unique_ptr'指向的'int'的地址。你想'ptr.get()' – user4581301

相关问题