简体   繁体   English

此代码中将调用哪个构造函数或赋值运算符?

[英]Which constructor or assignment operator is getting called in this code?

The output is 输出是

Constructor called 构造函数称为
20 20

When I am adding a copy-constructor, it is giving error " invalid initialization of non-const reference of type 'Foo&' from an rvalue of type 'Foo' " 当我添加一个复制构造函数时,它给出了错误“ 从类型为'Foo'的右值对类型'Foo&'的非常量引用进行了无效的初始化

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

There is no assignment in the code you posted. 您发布的代码中没有分配。 This: 这个:

  Foo F1 = static_cast<Foo>(20);

is alternate syntax for copy construction, and is an initialisation, not an assignment. 是复制构造的替代语法,并且是初始化而不是赋值。

Your problem with the copy constructor is probably caused by you defining it as 复制构造函数的问题可能是由于将其定义为

  Foo( Foo & f );

which prevents it from binding to temporary values. 这可以防止它绑定到临时值。 It should be: 它应该是:

  Foo( const Foo & f );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM