Martin Schlott
Martin Schlott

Reputation: 4547

Error with cast operator and std::string in a class

I broke down a problem I already tried to explain here in following problem:

#include <iostream>
#include <string>

class atest
{
public:
    operator std::string()
    {
        return std::string("Huhuhu");
    }
    operator int()
    {
        return 42;
    }
};

int main(int argc, char* argv[])
{
    atest tst;
    std::string astr;

    astr=tst;
    int i=0;
    i=tst;
    return 0;
}

std::string seems to have several constructors which even cover int. I got a class which need to be cast able to std::string but also to an integral type. As the assign (=) operator is not overide able outside a class definition I got no Idea how to get the above program running. It is bad design but it is worth noting that VS2013 has no problem with above code.

Upvotes: 1

Views: 63

Answers (1)

P0W
P0W

Reputation: 47804

You can use explicit conversion

explicit operator std::string()
~~~~~~~
{
    return std::string("Huhuhu");
}

Upvotes: 1

Related Questions