Reputation: 3366
Here's my code. This is boggling my mind.
#include <iostream>
#include <sstream>
#include <set>
#include <cmath>
#include <cstdlib>
#include "list.h"
#include "stack.h"
#include <limits>
#define PI 3.1415926535897932384626433832795
class RPN : public Stack<float> {
public:
std::string sqrt(float n);
};
std::string RPN::sqrt(float n){
std::string x;
x = sqrt(3.0);
std::ostringstream ss;
ss << n;
return (ss.str());
}
Yes that is compiling. sqrt is returning a string. trying to use a double or a float throws a strange error. Can anyone tell me what is going on? I've never had this before. The funny thing, is I'm actually converting to a string later on, but I doubt this will compile any where else...
postfix.cpp: In member function ‘std::string RPN::sqrt(float)’:
postfix.cpp:161:13: error: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘float’ in assignment
edit: posted wrong compiler error at first.
edit2: line 161 is n=sqrt(n); I have even tried double x = sqrt(n) and many other methods; Oh and when I print out the retrned string in my method posted above, I get a seg fault(obv..)
std::string RPN::sqrt(float n) {
n = sqrt(n);
std::ostringstream ss;
ss << n;
return (ss.str());
}
Upvotes: 0
Views: 194
Reputation: 7271
The line x = sqrt(3.0);
is calling your RDN::sqrt()
method which returns a string. I think you're trying to call the sqrt()
function in cmath. I would suggest renaming your method to something else. Alternatively, you might be able to call std::sqrt(3.0)
Upvotes: 3
Reputation: 1637
Let's look at the code more closely
std::string RPN::sqrt(float n){
std::string x; // temporary string variable
// calling sqrt with 3.0? What?
// This call actually would make this function be recursive
// (it would hide ::sqrt), making the assignment possible
// to compile (as sqrt returns a string)
// This also means that the function will
// eventually cause a stack overflow as there is no break case.
x = sqrt(3.0);
std::ostringstream ss; // temporary string stream
ss << n; // putting x in the string stream
// returning the string value of the string stream
// (i.e. converting x to a string)
return (ss.str());
}
In other words, there is no compile errors, but if you ran that code, you will get a run-time error.
EDIT:
Try n = ::sqrt(n)
(or n = std::sqrt(n)
if you #include <cmath>
) instead of n = sqrt(n)
, as that will just call your own function that you are defining, since your function will mask global scope.
n = sqrt(n)
makes your function recursive, and not compile.
Upvotes: 3