-3

I'm trying to solve the following problem from the lab where it says:

Define a class called Repository that has 2 integer private variables. The >class contains an empty constructor and another one with 2 parameters. An >accesor method that displays the variables values is also included in the >class. Write another class called Mathematics which is friend to the first >one. This class contains the implementation of the elementary arithmetical >operations (+, -, *, /) applied to the values stored in the first class. Each >arithmetical method receives as parameter an object instantiated from the >first class.

I have been searching all over the internet for a couple of hours already but I haven't found anything about overloading operators of a class in another one. I understand the overloading mechanism, I solved the problem using friend functions but I'm still asking myself if it is possible to do as above mentioned and if yes, I wish to know how to do it. Thanks in advance !

I have tried the solution mentioned here

//friend Repository operator + (Repository &, Repository &);
    friend Mathematics;
};
/*
Repository operator + (Repository &rep1, Repository &rep2)
{
    Repository obToRet;
    obToRet.val1 = rep1.val1 + rep2.val1;
    obToRet.val2 = rep1.val2 + rep2.val2;
    return obToRet;
}*/

class Mathematics
{
public:
    friend Repository;
    public static Repository operator+(Repository &rep1, Repository &rep2)
    {
        Repository objtoret;
        objtoret.val1 = rep1.val1 + rep2.val1;
        objtoret.val2 = rep1.val2 + rep2.val2;
        return objtoret;
    }
};
  • You've linked to a question with a C# tag, but tagged yours C++. The lab problem you have posted doesn't say "overloading operators of a class in another one"; it says mathematics has operators AND is a friend with the repository. – doctorlove May 01 '19 at 14:35
  • 2
    `Is it possible to overload operator of class A in a friend class B?` - no. The rest of the question is a mystery to me. – SergeyA May 01 '19 at 14:37
  • That sounds like some terrible instruction. C++ functions need not be chaperoned by classes – Caleth May 01 '19 at 14:49

1 Answers1

0

All that is asked is to implement the arithmetical operations. Not that you have to overload them:

#include <iostream>

class Mathematics;

class Repository
{
    friend Mathematics;
  private:
    int a;
    int b;

  public:
    Repository(int _a, int _b)
        :a(_a), b(_b) { }
};

class Mathematics
{

public:
    static int add(const Repository &rep)
    {
        return rep.a + rep.b;
    }
};

int main()
{
    Repository rep(1, 2);
    std::cout << Mathematics::add(rep);    
}
SilverTear
  • 695
  • 7
  • 18