U
U
User7002020-02-13 17:13:56
C++ / C#
User700, 2020-02-13 17:13:56

How to cast to default string?

#include <iostream>
#include <string>

class A {
private:
    std::string s = std::string("hello");
public:
    operator std::string& () {return s;}
    //operator const char* () {return s.c_str();}
};

int main() {
    A a;
    std::cout << a << '\n';
}


If you do not leave operator const char*, then "no known conversion for argument", although the conversion to std::string& is defined. Maybe the output operator for std::string is not defined? Changing the type to an unreferenced type or to a constant reference does not help. Though at operator const char* works.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
User700, 2020-05-15
@User700

So it's implicitly impossible.

B
byreoil, 2020-02-15
@byreoil

Need to explicitly convert for the cout operator

#include <iostream>
#include <string>

class A {
private:
    std::string s = std::string("hello");
public:
    operator std::string& () {return s;}
    //operator const char* () {return s.c_str();}
};

int main() {
    A a;
    std::cout << (std::string)a << '\n';
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question