Hello:
Does anyone know how to fix the code? It´s a calculator that uses different classes.
Here is what the compiler says when I try to compile:
no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'expression')
cout << "= " << expression(ts) << endl;
^
expression::expression is a constructor. Constructors are not allowed to return anything. The way you are using it, it seems that it shouldn't be in a class. Just make it a function on its own and give it a meaningful name.
Alternatively, inititalize the class in a ctor and overload operator().
1 2 3 4 5 6 7 8 9 10 11 12 13
class expression {
Token_stream &ts;
public:
expression(Token_stream &ts) : ts(ts) {}
doubleoperator();
}
double expression::operator() {
// your code here
}
expression e(ts);
cout << e() << '\n';
you said I should try to give it a function of its own with a meaninful name. Here is the problem:
I have 3 functions:
1.- expression. 2.- term. 3.- primary.
All of these functions depend on each other.
We were told we should do the calculator with the given classes "token" and "token_stream", and that we should add the functions in the main part.
When I tried to add the functions, if I put at first the expression function, it needed the term function. When writing the term function, it needed "primary" and when writing primary, it needed "expression".
Someone said one should create classes for each function and then add them in the main part with include, therefore I did them.
Now you say I should do this functions on their own but to be honest, where? I was thinking about creating a class named "functions" and then putting all of them there, but I´m not sure if we are allowed to change the code of the functions or if that´s the only way that exists to make the program run.
You're problem, as I understand it, is that you have three functions that create a circular dependency. That's easy to deal with. Just put the function prototypes above the functions.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
// function prototypes
int f(int n);
int g(int n);
int h(int n);
int main() { std::cout << f(1) << '\n'; }
int f(int n) { return n > 3 ? n : g(n); } // f knows about g because of the prototype
int g(int n) { return h(n+1); } // g knows about h because of the prototype
int h(int n) { return f(n+1); } // h would know about f even without the prototype,
// but it's still a good idea to have its prototype anyway