C ++拷贝构造函数错误:成员分配' Fraction ::分子'在只读对象中

时间:2016-07-03 07:47:30

标签: c++ copy-constructor

我的页眉文件:

#include <iostream>
using namespace std;

class Fraction
{
private:
    double numerator;
    double denominator;
public:
    Fraction();
    ~Fraction();
    Fraction(const Fraction& c);
    Fraction(double,double);
    //setter
    void setNumerator(double newnumerator);
    void setDenominator(double newdenominator);
    //getter
    double getNumerator();
    double getDenominator();

    //friend overlaoding operators

    friend ostream& operator<<(ostream& os, Fraction f);

};

我的CPP文件:

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

using namespace std;

Fraction::Fraction()
{
    cout<<"Empty constructor called"<<endl;
}

Fraction::~Fraction()
{
    cout<<"Deconstructor called"<<endl;
}

Fraction::Fraction(const Fraction& c)
{
    c.numerator = numerator;
    c.denominator = denominator;
}

Fraction::Fraction(double newnumerator, double newdenominator)
{
    numerator = newnumerator;
    denominator = newdenominator;
}

void Fraction::setNumerator(double newnumerator)
{
    numerator = newnumerator;
}

void Fraction::setDenominator(double newdenominator)
{
    denominator = newdenominator;
}

double Fraction::getNumerator()
{
    return numerator;
}

double Fraction::getDenominator()
{
    return denominator;
}

ostream& operator<<(ostream& os, Fraction f)
{
     os<<f.numerator<<"/"<<f.denominator<<endl;
     return os;
}

我的testcpp.file:

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

using namespace std;

int main()
{
    Fraction f1;

    cout<<f1;

    return 0;
}

当我运行此代码时,我得到error消息:

  

Fraction.cpp:在复制构造函数'Fraction :: Fraction(const Fraction&amp;)'中:   Fraction.cpp:20:17:错误:在只读对象中分配成员'Fraction :: numerator'            c.numerator = numerator;

     

Fraction.cpp:21:19:错误:在只读对象中分配成员'Fraction :: denominator'            c.denominator = denominator;

PS:一旦我遗漏了复制拷贝构造函数并尝试其余部分确实有效,但我得到重载运算符的相同error消息cin >>)。

非常感谢。

2 个答案:

答案 0 :(得分:2)

您的复制构造函数是向后的。您应该从参数化实例复制到this实例。

Fraction::Fraction(const Fraction& c)
{
    numerator = c.numerator;
    denominator = c.denominator;
}

答案 1 :(得分:0)

摆脱const并放一个ref。分数旁边的&symbol。为什么?对对象进行更改?

friend istream& operator>>(istream &is, Fraction &f);

istream& operator>>(istream &is, Fraction &)
{

    cout<<"Enter numerator"<<endl;
    is>>f.numerator;
    cout<<"Enter denominator"<<endl;
    is>>f.denominator;

    return is;
}