use ostream overloading to ouput char* and use constructor to initialize char*

  c++, char
class MyStr
{
    char* name;
    int id;
public:
MyStr(int _id, char* _name) 
    { 
        cout << "constructor" << endl;
        id = _id;
        name = new char[strlen(_name) + 1];
        strcpy_s(name, strlen(_name) + 1, _name);
    }
friend ostream& operator << (ostream& out, const MyStr& obj);
}
ostream& operator << (ostream& out, const MyStr& obj)
{
    out << obj.id<<obj.name;//why compiler told me it invoked a breakpoint here
    return out;
}
int main()
{
MyStr str1(1,"hi");//compiler says "hi" is const char[] and not match char*
}

I have two questions about char*. First, how can I initialize char * in main function using user defined constructor function so that I can set different names for more than one objects. Second, I want to know how to use ostream operator overloading to ouput a char*.

Source: Windows Questions C++

LEAVE A COMMENT