-2
#include"stdafx.h"
#include<iostream>
class Item
{
 int exponent;
 double coefficient;     //two private members 
 public:
 //constructor
 Item(int exp = 0, int coef = 0) :exponent(exp), coefficient(coef) {}
 Item(Item& item) {
    exponent = item.exponent;
    coefficient = item.coefficient;
 }                                      //copy constructor
 //interface to change private member exponent
 void change_exp(const int n) {           
    Item::exponent = n;
 }
 //interface to change private member coefficient
 void change_coef(const double n) {
    Item::coefficient = n;
 }
 int get_exp() { return exponent; }// interface to get exponent
 double get_coef() { return coefficient; }//  interface to get coefficient
 ~Item() {}
 Item operator=(Item item2) {
    change_exp(item2.get_exp());
    change_coef(item2.get_coef());
    return (*this);
 }
 Item operator*(Item & item2) {
    Item result;
    result.change_coef(coefficient * item2.get_coef());
    result.change_exp(exponent + item2.get_exp());
    return result;
 }
 };
 int main() {
 Item test(2, 7);
 Item test2(4, 5);
 Item result;
 result = test * test2;    //BUG!!! 
 return 0;
 }

the bug appears on the line commented BUG Error C2679 binary '=': no operator found which takes a right-hand operand of type 'Item' (or there is no acceptable conversion)
when I only assign one object like result=test; it is fine. I dont know where went wrong in my = overloading function. Please help......

Owen Wong
  • 1
  • 2

2 Answers2

1

You need to declare your copy constructor as Item(const Item& item).

The result of test * test2 is a temporary rvalue without an address so you can't create a (lvalue) reference to it. It is however allowed to create a const reference.

This question and answer might yield more information related to this topic: c++: const reference to an rvalue

Devon Cornwall
  • 957
  • 1
  • 7
  • 17
0

There are so many things wrong with your code.

  • Firstly, you should be respectful to the naming conventions like accessor and mutator methods. You should name your accessor method setExp not change_exp.

  • Secondly, you should know when to overload things like assignment operator (please google big three in c++). Basically, you don't have to overload assignment operator if you have only primitive types of fields.

  • Lastly, you must use const qualifier when ever possible. For example at the end of your accessor methods, in front of the argument for copy contructor, etc..

Your copy constructor should look like

Item(const Item& item) {
    exponent = item.exponent;
    coefficient = item.coefficient;
 }   

Your assignment operator should look like

Item& operator=(const Item& item2) {
    change_exp(item2.get_exp());
    change_coef(item2.get_coef());
    return (*this);
 }

Your accessor method for field coefficient look like

double getCoefficient() const { return coefficient; }//  interface to get coefficient
eneski
  • 1,575
  • 17
  • 40