为什么mpz_class内部的值被更改

问题描述 投票:0回答:1

我正在新使用C ++。当我尝试添加运算符重载时出现问题。根据我的实现,结果对象必须等于[0 1 1 0] [(0 1 1 0)(2423 575 0 0)(466 3465664 0 0)] [2423 575 0 0]。 (您可以认为我的插图是这样[this] [x] [y])但是,当我调试它时,内部结果像[0 1 1 0] [(0 1 0 0)(2423 575 0 0)(466 3465664 0 0)] [2423 575 0 0]。因此,result-> x-> c是错误的,它必须为1,但变为0。为什么会这样?我不明白是怎么了。你可以帮帮我吗?顺便说一句,我使用的是Apple LLVM版本9.0.0,c ++ 17和cmake版本3.17.0。

#include "gmpxx.h"
#include "Matrix.h"


int main() {
   mpz_class n1,d1,n2,d2;
   n1 = 2423;
   d1 = 575;
   n2 = 466;
   d2 = 3465664;

   Matrix<mpz_class> num1(n1,d1);
   Matrix<mpz_class> num2(n2,d2);
   Matrix<mpz_class> num3(n1,d1);
   Matrix<mpz_class> result = num1 + num2 + num3;

    return 0;
}

template<typename coefficient>
class Matrix{
private:
    coefficient a;
    coefficient b;
    coefficient c;
    coefficient d;
    Matrix<coefficient> *x = nullptr;
    Matrix<coefficient> *y = nullptr;

public:
Matrix(){
    this->a = 0;
    this->b = 0;
    this->c = 0;
    this->d = 0;
}

Matrix(coefficient ax,coefficient bx){
this->a = ax;
this->b = bx;
this->c = 0;
this->d = 0;
}


Matrix(coefficient ax,coefficient bx, coefficient cx, coefficient dx,Matrix<coefficient> *x,Matrix<coefficient> *y){
    this->a = ax;
    this->b = bx;
    this->c = cx;
    this->d = dx;
    this->x = x;
    this->y = y;
}

Matrix<coefficient> operator+(const Matrix<coefficient> &other) {
    Matrix<coefficient> *ptr = const_cast<Matrix<coefficient>*>(&other);
    return Matrix<coefficient>(0, 1, 1, 0, this, ptr);
}
};

c++ gmp
1个回答
0
投票
表达式

num1 + num2 + num3

相当于

num1.operator+(num2.operator+(num3))

这里的问题是num2.operator+(num3)将返回一个正在传递给num1.operator+()

temporary对象。

临时对象的生存期一直到完整表达式的末尾,这意味着一旦num1.operator+(num2.operator+(num3))完成,它将被销毁,您保存到该对象的任何指针都将变为无效。

然后您

do

通过将指向other(这是对临时对象的引用)的指针传递到最后一个构造函数,并将其保存在this->y中,从而保存了指向该临时对象的指针。一个简单的解决方案可能是根本不使用指针,而是复制整个对象。
© www.soinside.com 2019 - 2024. All rights reserved.