繁体   English   中英

定义赋值运算符和复制构造函数

[英]Defining both Assignment operator and copy constructor

假设我有一个类A。我定义了一个复制构造函数和一个赋值运算符重载函数。 当我做

A类; B类= A;

然后在定义B类时,是调用复制构造函数还是赋值运算符?

提前致谢。

编辑:对不起,我提到了错误的代码。 它应该是:

A a; a b = a;

IIRC T t = value调用复制构造函数,可以通过在构造函数中输出字符串以确定所使用的方法来进行验证。 IIRC当声明和赋值在同一行时,它不称为赋值,而是初始化。

另一方面,您发布的内容没有任何意义,您不能将一个类型分配给另一种类型,只能分配给类型实例。

编辑:即使您有两种不同类型的情况(您的问题的上下文对此不清楚):

class A {};

class B {
public:
   B(const A& other)  { cout << "copy"; }
   B& operator=(const A& other) { cout << "assign"; }
};

int main() {
   A a;
   B b = a; // copy con
   B b1(a); // same as above
   b = a;   // assign op
}

即使这样,当“复制构造函数”和赋值运算符都采用另一种类型时,仍将调用复制构造函数而不是赋值运算符。

假设您实际上的意思是:

A a;
A b = a;

复制构造函数被调用。 标准在此用法中允许=此特殊含义。

使用两者创建一个简单的类,并通过在两者中设置一个断点来调试要执行的功能。 然后您将看到,并且还将学习一些调试。

让我们尝试一下!

#include <iostream>

class A {
 public:
  A() {
    std::cout << "default constructor\n";
  }
  A(const A& other) {
    std::cout << "copy constructor\n";
  }
  A& operator=(const A& rhs) {
    std::cout << "assignment operator\n";
    return *this;
  }
};

int main(int argc, char** argv) {
  std::cout << "first declaration: ";
  A a;
  std::cout << "second declaration: ";
  A b(a);
  std::cout << "third declaration: ";
  A c = a;
  std::cout << "fourth declaration: ";
  A d;
  std::cout << "copying? ";
  d = a;
  return 0;
}

打印:

first declaration: default constructor
second declaration: copy constructor
third declaration: copy constructor
fourth declaration: default constructor
copying? assignment operator

这里的工作示例: http : //codepad.org/DNCpqK2E

当您定义新对象并为其分配另一个对象时。 它调用复制构造函数。 例如,复制构造函数调用:

Class A;
Class B=A;

分配操作员呼叫:

Class A;
Class B;
B=A;

您始终可以通过在两种方法中编写“ print”语句来找出正在调用的方法来进行测试。

希望能有所帮助...

暂无
暂无

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

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