May 9, 2014 at 1:10pm UTC
Last edited on May 9, 2014 at 1:15pm UTC
May 10, 2014 at 4:53pm UTC
How i can use std::string operator std::string() ?
When put in code gcc tells me error
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
struct Fr
{
int num;
int denom;
Fr(int i,int j)
{
num=i;
denom=j;
}
Fr(){};
std::string operator std::string()
{
return (std::to_string(num) + "/" + std::to_string(denom));
}
};
error: return type specified for 'operator std::string {aka std::basic_string<char>}'|
Last edited on May 10, 2014 at 4:57pm UTC
May 11, 2014 at 2:35am UTC
He means you need to enable C++ 11 with the -std=c++11 flag (I believe).
May 11, 2014 at 3:02am UTC
No, that is wrong. You don't specify a return type for the operator. Here is an example of what you can do:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <string>
#include <iostream>
struct Fr
{
int num;
int denom;
Fr(int i,int j)
{
num=i;
denom=j;
}
Fr(){};
/* std::string */ operator std::string()
{
return (std::to_string(num) + "/" + std::to_string(denom));
}
};
std::ostream& operator << (std::ostream& o, const Fr& f) {
o << f.num << '/' << f.denom;
return o;
}
int main() {
Fr f (4, 9);
std::string s = f;
std::cout << s << std::endl;
std::cout << f << std::endl;
return 0;
}
4/9
4/9
http://coliru.stacked-crooked.com/a/c7c760a201b38d67
Note that by defining
operator<< for your class as well, you can use your original stringstream
method to convert into a string as well.
Last edited on May 11, 2014 at 3:04am UTC
May 11, 2014 at 11:43pm UTC
Sorry, I didn't know the cast operator don't need a return, but it is kind obvious. (cast to std::string would return int?!?)
May 12, 2014 at 12:41am UTC
Depending on what you're doing, it could.
May 12, 2014 at 7:10am UTC
Very helpful, thank you all.
I have try compilation and is ok.
Thank you.
Last edited on May 12, 2014 at 7:10am UTC
May 13, 2014 at 5:17pm UTC
Huh, how @Avillius? If I want to cast my class to std::string , it's obvious it would return int! </sarcasm>