Could you please help me to resolve the error in the below code.
class Mstream{
unsigned int len;
char *str;
};
int main(){
Mstream m1;
std::string str=m1;// i see error at this statement
}
error:
conversion from 'Mstream' to non-scalar type 'std::string {aka std::basic_string<char>}' requested
std::string
does not have a constructor or operator=
that takes an Mstream
as input. It does, however, have a constructor that takes a char*
and size as input:
int main(){
Mstream m1;
std::string str(m1.str, m1.len);
}
Alternatively, you can add a std::string
conversion operator to Mstream
, then you can assign an Mstream
to a std::string
:
class Mstream{
unsigned int len;
char *str;
operator std::string() const { return std::string(str, len); }
};
int main(){
Mstream m1;
std::string str = m1;
}
Either way, do make sure the Mstream
is properly initialized with a valid char*
pointer and length value before attempting to do the conversion to std::string
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.