【问题标题】:Which constructor or assignment operator is getting called in this code?在这段代码中调用了哪个构造函数或赋值运算符?
【发布时间】:2017-08-10 19:53:29
【问题描述】:

输出是

构造函数调用
20

当我添加一个复制构造函数时,它给出了错误“invalid initialization of non-const reference of type of 'Foo&' from an rvalue of a rvalue

  #include <iostream>
  using namespace std;

  class Foo
  {

  int a;
  public:
    Foo(int a)
    {
        this->a =a;
        cout<<"Constructor called\n";
    }
    void operator=(Foo f)
    {
        this->a = a;
        cout<< "Assignment operator called";
    }
    void show()
    {
        cout<<this->a<<endl;
    }

  };


  int main() 
  {
    // your code goes here
    Foo F1 = static_cast<Foo>(20);
    F1.show();
    return 0;
  }

【问题讨论】:

    标签: c++ copy-constructor assignment-operator


    【解决方案1】:

    您发布的代码中没有分配。这个:

      Foo F1 = static_cast<Foo>(20);
    

    是复制构造的替代语法,是初始化,而不是赋值。

    复制构造函数的问题可能是由于您将其定义为

      Foo( Foo & f );
    

    这会阻止它绑定到临时值。应该是:

      Foo( const Foo & f );
    

    【讨论】:

    • 是的,我的复制构造函数是Foo(Foo & f);
    • 谢谢,尼尔。但是添加 const 是如何解决 r 值问题的呢?
    • 标准规定只有 const 引用可以绑定到右值。在这种情况下特别有意义,因为复制构造函数通常不能更改被复制的内容。
    猜你喜欢
    • 1970-01-01
    • 2011-02-20
    • 2017-10-06
    • 1970-01-01
    • 2013-03-26
    • 2011-02-08
    • 2013-03-07
    • 2011-05-21
    • 2013-07-03
    相关资源
    最近更新 更多