-1

I have a class with 3 fields a,b and c. I want to calculate the volume of a box with sides a,b or c. I want to do this with a friend function. However, when I compile the program the Compiler gives an error No global operator found which takes type Box. I would like to ask why is that?

#include "pch.h"
#include <iostream>
using namespace std;
class Box {
    double a, b, c;
    public:
    Box(double sa, double sb, double sc) {
            a = sa;
            b = sb;
            c = sc;
    }
    friend double calcVolume(Box bx) {
    return bx.a*bx.b*bx.c;

    };

};

int main() {
    Box a(5.67, 6.43, 7.00),b(90,32.76,44.18);
    cout << calcVolume(a)<<endl;


    return 0;
}
A.Dimitrov
  • 109
  • 2
  • 2
  • 9
  • 1
    there is typo in code, change return bx.a*bx.b*bx*c; to return bx.a * bx.b * bx.c; – Amol Saindane Sep 26 '18 at 04:46
  • Cannot reproduce after commenting `#include "pch.h"`. The error is likely to lie inside that piece of code that you neither use nor show here... VTC for that reason. – Serge Ballesta Sep 26 '18 at 05:37

2 Answers2

1

There is a mistake in you code return bx.a*bx.b*bx*c;, which should be return bx.a*bx.b*bx.c; (the last dot)

#include <iostream>

using namespace std;

class Box {
    double a, b, c;
    public:
    Box(double sa, double sb, double sc) {
            a = sa;
            b = sb;
            c = sc;
    }
    friend double calcVolume(Box &bx) {
        return bx.a * bx.b * bx.c;
    };
};

int main() {
    Box a(5.67, 6.43, 7.00),b(90,32.76,44.18);
    cout << calcVolume(a)<<endl;
    return 0;
}
shawn
  • 4,305
  • 1
  • 17
  • 25
0

A couple of things : use const when you are not modifying the argument, second do not do using namespace std. Now, this works for me

#include <iostream> 

class Box 
{ 
    double a; 
    double b; 
    double c; 
public: 
    Box(double ain, double bin, double cin) {a = ain; b = bin; c = cin;} 
    friend double calcVol(const Box& rOther)
    {
        return rOther.a*rOther.b*rOther.c;
    }
}; 

int main() 
{ 
    Box a(14.8, 10.8, 11.01), b(8,5.0,6.2); 
    std::cout<<"vol a :: "<<calcVol(a)<<std::endl; 
    std::cout<<"vol b :: "<<calcVol(b)<<std::endl; 

    return 0; 
}
AdityaG
  • 428
  • 1
  • 3
  • 17