重载<<操作员意外行为?

时间:2017-05-30 12:12:00

标签: c++ g++

我为我的项目编写了bigInteger算法:

.hpp文件:

#include<iostream>
  #include<vector>
  #include<string>
  #include<algorithm>

  using namespace std;

  class BigInteger{
    private:
      vector<int> digits;
    public:
      BigInteger(){}
      BigInteger(string input);
      BigInteger(int input);
      friend BigInteger operator+(BigInteger &lhs, BigInteger &rhs);
      BigInteger operator=(BigInteger &rhs);
      friend ostream &operator<<(ostream &out, BigInteger &t);
      vector<int> getDigits();
      int getNum(int t);
      void setDigits(vector<int> &vect);
      void handleCarry(BigInteger &t);
  };

.cpp文件:

#include "BigInteger.hpp"

BigInteger::BigInteger(string input){
 int temp;·
 for(int i = input.size()-1; i >= 0; i--){
  temp = input[i] - '0';
  digits.push_back(temp);
 }
}

BigInteger::BigInteger(int input){
  int temp = input;
  while(temp){
    digits.push_back(temp%10);
    temp = temp/10;
  }
}

vector<int> BigInteger::getDigits(){
 return digits;
}

void BigInteger::setDigits(vector<int> &vect){
  digits = vect;
}

void BigInteger::handleCarry(BigInteger &t){
  vector<int> temp = t.getDigits();
  int len = temp.size();

  int num = 0;

  for(int i = 0; i < len; i++){
    carry = temp[i]/10;
    num = temp[i]%10;
    temp[i] = num;

    if((len -1) == i && carry > 0){
       temp.push_back(carry);
    }
    else
      temp[i+1] += carry;
  }
  t.setDigits(temp);
}

BigInteger operator+(BigInteger &lhs, BigInteger &rhs){
  int len = lhs.getDigits().size() > rhs.getDigits().size()? lhs.getDigits().size():rhs.getDigits().size();
  BigInteger result;
  vector<int> tmp;
  for(int i = 0; i < len; i++){
      tmp.push_back(lhs.getNum(i) + rhs.getNum(i));
  }
  result.setDigits(tmp);
  result.handleCarry(result);
  return result;
}

BigInteger BigInteger::operator=(BigInteger &rhs){
  vector<int> temp(rhs.getDigits());
  this->setDigits(temp);
  return *this;
}
ostream &operator<<(ostream &out, BigInteger &t){
  for(int i = t.getDigits().size()- 1; i >= 0; i--){
   out << t.getDigits()[i];
  }
 cout << endl;
  return out;
}

Main.cpp的:

#include "BigInteger.hpp"

int main(){
BigInteger t("123");
BigInteger u(234);
BigInteger r = t + u;
cout << r << endl;
cout << t + u << endl;

return 0;
}

所需的结果是在coutmain()语句的两种情况下打印结果,如:

 cout << t + u << endl;
 or 
 r = t + u;
 cout << r << endl;

但是,第一句话是错误地说no match for operator<<

获得理想结果缺少什么?

2 个答案:

答案 0 :(得分:3)

.这会返回一个无法绑定到t + u所要求的左值引用的临时值,您需要添加operator<<(ostream &out, BigInteger &t)

const

这应该是流操作符的默认值,因为您不应该想要更改此对象的状态。

答案 1 :(得分:1)

您的输出操作符应采用const引用:

import CryptoJS from 'crypto-js'; 

import CryptoBrowserify from 'crypto-browserify';

var encrypted = CryptoBrowserify.publicEncrypt( publicKey,new Buffer(data));

你不能对ostream &operator<<(ostream &out,const BigInteger &t) ^^ 采用非const引用,因为它是一个r值,但是你可以将一个const-ref绑定到一个r值。