2016-09-18 110 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

相關問題