* about constructor and switch
@ 2004-09-09 8:19 learning c++
2004-09-09 11:54 ` Eljay Love-Jensen
0 siblings, 1 reply; 2+ messages in thread
From: learning c++ @ 2004-09-09 8:19 UTC (permalink / raw)
To: gcc-help
Hi, I compiled a short code. But it does not work.
There are something wrong in constructor, substr and switch.
10.11.cpp: In member function `int Expr::eval()':
10.11.cpp:28: error: switch quantity not an integer
#include <iostream>
#include <string>
using namespace std;
class Expr{
int val1, val2, value;
string s1;
public:
Expr(const string);
int eval();
void print();
};
Expr::Expr(const string s){
string::iterator iter1;
for(iter1=s.begin();iter1!=s.end();iter1++){
if(!isdigit(*iter1))
val1=(int)s.substr(s.begin(),iter1-1);
val2=(int)s.substr(iter1+1,s.end());
s1=*iter1;
}
}
int Expr::eval(){
switch(s1){
case "+":
value=val1+val2;
return value;
break;
case "*":
value=val1*val2;
return value;
break;
case "-":
value=val1-val2;
return value;
break;
case "/":
value=val1/val2;
return value;
break;
}
}
int main(){
int output;
Expr input("5+3");
output=input.eval();
cout<<"The result is: "<<output<<endl;
return 0;
}
_________________________________________________________________
Add photos to your messages with MSN 8. Get 2 months FREE*.
http://join.msn.com/?page=features/featuredemail
^ permalink raw reply [flat|nested] 2+ messages in thread
* Re: about constructor and switch
2004-09-09 8:19 about constructor and switch learning c++
@ 2004-09-09 11:54 ` Eljay Love-Jensen
0 siblings, 0 replies; 2+ messages in thread
From: Eljay Love-Jensen @ 2004-09-09 11:54 UTC (permalink / raw)
To: learning c++, gcc-help
Hi,
The switch C/C++ construct can only take an integer.
It cannot take an object (unless that object is convertible to an
integer). Thus, it cannot take a std::string.
It cannot take a float, double, long double. Or a complex. Or a pointer.
It can take a char, short, int, long or bool, or any expression which
evaluates to such.
Some languages, such as Ada, have a more capable switch construct, which
can handle those other situations that C/C++ cannot.
For those more complicated situations in C/C++, use a if/else if/else
construct, or use polymorphism (where applicable).
HTH,
--Eljay
^ permalink raw reply [flat|nested] 2+ messages in thread
end of thread, other threads:[~2004-09-09 11:54 UTC | newest]
Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2004-09-09 8:19 about constructor and switch learning c++
2004-09-09 11:54 ` Eljay Love-Jensen
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).