c++ - 在 C++ 类中重载交换函数

标签 c++

我正在尝试实现一个交换函数,它会覆盖复制构造函数并最终允许我使用等于“=”运算符。问题是在测试我的交换函数时,我得到了其他所有东西的垃圾值(isNeg 是一个 bool,digits 是一个 unsiged int* 数组,numDigits 是 数字。
ReallyLongInt 是一个 Unsigned Int* 大小为 numDigits 的数组,我已经彻底测试了我的构造函数,它们适用于字符串和 long longs。

这是声明(ReallyLongInt.cc):

void ReallyLongInt::swap(ReallyLongInt other)
{

  //Sets temporary values to equal others values
  unsigned int* temp = new unsigned int[this->numDigits];

  std::swap(this->digits, other.digits);
  std::swap(this->numDigits, other.numDigits);
  std::swap(this->isNeg, other.isNeg);

 }

和我用来测试的 main (main.cc)

#include "ReallyLongInt.h"
#include <iostream>


using namespace std;


int main(int argc, char** argv){
  string a = "56789";
  long long b = 123456;


  ReallyLongInt x = ReallyLongInt(a);
  ReallyLongInt y = ReallyLongInt(b);
  cout<<"a: "<<x<<endl;
  cout<<"b: "<<y<<endl;
  y.swap(x);

  cout <<"b after swapping with a:  "<< y <<endl;


}

我认为问题在于我传递给交换调用的值

y.swap(x)

但是当我运行代码时,this->numDigits 的大小是垃圾,并且由于这个数字干扰了我的打印功能,我得到了一个 segFault。

最佳答案

void ReallyLongInt::swap(ReallyLongInt other)

任何指定参数“按值传递”的函数都意味着每次调用该函数时都会初始化一个新拷贝。因此,当您调用 y.swap(x) 时,您正在修改一个函数局部变量 other,而不是您想要的对象 x .

要允许函数修改传入的对象,您应该改用引用参数:

void ReallyLongInt::swap(ReallyLongInt& other);

顺便说一下,一些标准函数检查的 swap 的正常形式是一个带两个参数的非成员函数。所以在课外:

void swap(ReallyLongInt& a, ReallyLongInt& b);

如果愿意,您可以根据成员swap 实现非成员swap

关于c++ - 在 C++ 类中重载交换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46394696/

相关文章:

c++ - 所有连续子数组优化的总和

c++ - 为什么我的数组不存储任何输入值?

c++ - 使用 Armadillo 类型的 lambda 函数崩溃的未知原因

c++ - 变量值的后缀#DEN 是什么意思

c++ - g++ ifstream匹配错误

c++ - Qt 显示超大富文本的最佳方式?

c++ - shuffle/permute 内在函数如何为 256 位 pd 工作?

c++ - 用CMake生成自定义头文件

c++ - strcpy_s 不适用于 gcc

c++ - VC2013 move 运算符不递归执行 move