【问题标题】:copy constructor gives compilation error复制构造函数给出编译错误
【发布时间】:2016-12-23 16:54:27
【问题描述】:
  void print_me_bad( std::string& s ) {
      std::cout << s << std::endl;
  }

  void print_me_good( const std::string& s ) {
      std::cout << s << std::endl;
  }

  std::string hello( "Hello" );

  print_me_bad( hello );  // Compiles ok
  print_me_bad( std::string( "World" ) );  // Compile error
  print_me_bad( "!" ); // Compile error; 
  print_me_good( hello ); // Compiles ok

  print_me_good( std::string( "World" ) ); // Compiles ok
  print_me_good( "!" ); // Compiles ok 

在上面的复制构造函数程序中,为什么我在传递“世界”时会出现第二种情况的编译错误?

【问题讨论】:

  • 临时不能绑定到非常量的引用。
  • 您显示的代码中的任何地方都没有复制构造。问题与左值和右值(基本上是“临时”对象)之间的差异以及对常量和非常量对象的引用之间的差异有关。
  • 将临时对象绑定到引用(需要const)-herbsutter.com/2008/01/01/…

标签: c++ reference constants copy-constructor temporary


【解决方案1】:

如 cmets 中所述,您不能将临时对象绑定到非 const 引用。

以下情况:

print_me_bad( std::string( "World" ) );  // Compile error
print_me_bad( "!" ); // Compile error; 

你创建了一个临时的 std::string 对象。首先显式 (std::string( "World" )) 然后通过隐式转换 ("!" 转换为 std::string)。这是不允许的。

但是,您可以将临时变量绑定到 const 引用,这就是其他情况编译得很好的原因:

print_me_good( std::string( "World" ) ); // Compiles ok
print_me_good( "!" ); // Compiles ok 

【讨论】:

    猜你喜欢
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    相关资源
    最近更新 更多