c++ - C++语法和编译器错误-运算符<<不匹配

标签 c++ compiler-errors c++14

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;

}

最佳答案

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;
}

关于c++ - C++语法和编译器错误-运算符<<不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553243/

相关文章:

linux - 海合会 : error trying to exec 'cc1' when cross-compiling

java - 泛型问题 - 无法编译代码,可能是由于类型删除

scala - 隐式转换不明确,因此不适用

c++ - 分配给在表达式右侧移动的变量

c++ - 迭代器的默认值是多少?

c++ - 在CMAKE中制作程序之前如何制作一个库?

c++ - Botan SSL/TLS 示例或起点

c++ - 为什么 clock() 在集群机器上不起作用

私有(private)成员的 C++14 单元测试(解除)分配

c++ - 在 c++14 lambda 表达式中捕获和移动 unique_ptr