WholeNumbers类的类型的引用的无效初始化

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

我正在尝试编写一个名为WholeNumber的类。我还没有完成编写,我想尝试频繁地编译,以便使错误保持在低水平并易于管理。当我直接编译类时,出现此错误:

fibonacci.cpp:在成员函数‘std :: __ cxx11 :: list&WholeNumber :: operator =(WholeNumber&)'中:fibonacci.cpp:41:14:错误:类型'WholeNumber'的表达式中对类型'std :: __ cxx11 :: list&'的引用的初始化无效返回* this;

我尝试查找错误,以查看是否可以找到问题的答案,但是我只能发现您无法从const引用中初始化非const引用。我不明白这可能是指我的代码。我想念什么?

#include <iostream>
#include "fibonacci.h"   // for fibonacci() prototype                                                                                                     
#include <list>
#include <vector>
using namespace std;

class WholeNumber
{
private:
   list <int>  digits;

public:
   //default constructor                                                                        
   WholeNumber() { }
   //non-default constructor                                                                    
   WholeNumber(unsigned int number) {number = 0;}
   //copy constructor                                                                           
   WholeNumber(const WholeNumber & rhs) { }
   //destructor                                                                                 
   ~WholeNumber() { }


   friend ostream & operator << (ostream & out, const list <int> * l);
   istream &  operator >> (istream & in);
    WholeNumber & operator +=(const WholeNumber & rhs);

   list <int> & operator = (WholeNumber & rhs)
   {
      this->digits = rhs.digits;
      return *this;
   }

};

c++ class operator-overloading operators definition
1个回答
1
投票

副本分配运算符的返回类型为list <int> &

   list <int> & operator = (WholeNumber & rhs)
   {
      this->digits = rhs.digits;
      return *this;
   }

但是返回类型为WholeNumber*this)的对象,并且没有从一种类型到另一种类型的隐式转换。

也许您是说以下

   WholeNumber & operator = ( const WholeNumber & rhs )
   {
      this->digits = rhs.digits;
      return *this;
   }

也这些运算符

   friend ostream & operator << (ostream & out, const list <int> * l);
   istream &  operator >> (istream & in);

无效。例如,第一个运算符应声明为

   friend ostream & operator << (ostream & out, const WholeNumber & );

第二个运算符也应该是类似的朋友函数

   friend istream &  operator >> ( istream & in, WholeNumber & );
© www.soinside.com 2019 - 2024. All rights reserved.