我正在尝试实现一个交换函数,它会覆盖复制构造函数并最终允许我使用等于“=”运算符。问题是在测试我的交换函数时,我得到了其他所有东西的垃圾值(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/