This is a c++ char generator initialization question

Asked 2 years ago, Updated 2 years ago, 81 views

#include<iostream>
using namespace std;

class Test{
    private:
        char* str;
    public:
        Test(char* name){
    str=name;
        }
        void hello(void){
            cout << str;
        }
};

int main(){
    Test ptr("lee");
    ptr.hello();
    return 0;
}

I declared char as a member variable [Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings] The message pops up like this is it Char hyung is curious how to initialize the constructor. Also, I would like to know why char type has a problem with initialization.

constructor initialization char

2022-09-22 18:21

2 Answers

First, the string is a constant.

You have to put a const.

const char* name

And I recommend using string to handle strings.


2022-09-22 18:21

Do it as below.

#include<iostream>
using namespace std;

class Test{
    private:
        const char* str;
    public:
        Test(const char* name){
            str = name;
        }
        void hello(void){
            cout << str;
        }
};

int main(){
    Test ptr("lee");
    ptr.hello();
    return 0;
}


2022-09-22 18:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.