Search code examples
c++access-specifiertypecast-operator

Creating class operator


Trying to create class operator:

class ggg
    {
    int a;
    int b;
    operator std::string ( ) 
        {
        return "hello";
        }

    };

int main() {

    ggg g ;
    std::string s =  g;
    cout<<s;

}

and got error:

'ggg::operator std::string' : cannot access private member declared in class 'ggg'  

How to solve this problem?


Solution

  • All members in classes are private by default.

    class ggg
    {
        int a;
        int b;
    public:
        operator std::string ( ) 
        {
            return "hello";
        }
    
    };
    

    should solve your problems