LBaelish
LBaelish

Reputation: 689

Overloading bitwise & c++ as non-member function

Trying to overload bitwise & in c++ as a non-member function

myClass.h

class myClass
{
     public:
     myClass(double);
     void setSomeValue(double);
     double getSomeValue() const{
        return someValue;
     }
     /*...more methods...*/


      private:
      double someValue;
};

myClass.cpp

myClass::myClass(double someValue){
    setSomeValue(someValue);
}
myClass::setSomeValue(double someValue){
    this->someValue = someValue;
}
double operator&(myClass &lhs, myClass &rhs){
    return lhs.getSomeValue() * rhs.getSomeValue();

}

I was told I should be able to have a non member function that's not declared as a friend by accessing a classes private members through the classes getters. However when I try:

int main(){
    myClass A(0.1);
    myClass B(0.1);

    double test = A & B;
 }

I just get an error message that says no operator "&"matches these operands. How can I make this work/what am I doing wrong?

Upvotes: 0

Views: 214

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Here's a fixed version of your code example (I couldn't reproduce the no operator "&"matches these operands error message at any stage though):

myClass.h

class myClass
{
     public:
     myClass() : someValue() {}
     double getSomeValue() const{
        return someValue;
     }
     //...more methods...//


      private:
      double someValue;
};

// ***********************************************************************************
// * You need to make that global operator override visible through the header file: *
// ***********************************************************************************
inline double operator&(myClass &lhs, myClass &rhs){
    return lhs.getSomeValue() * rhs.getSomeValue();

}

main.cpp

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

int main(){
    myClass A;
    myClass B;

    double test = A & B;
    std::cout << test << std::endl;

 }

Live Demo

Upvotes: 1

Peter Barmettler
Peter Barmettler

Reputation: 611

I guess you do not include a declaration of your & operator in your main program. Try to place

double operator&(myClass &lhs, myClass &rhs);

in your myClass.h file.

Upvotes: 2

Related Questions