It's a generator and an extinction exercise. I'm asking you a question because I'm curious about other ways

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

#include <iostream>
#include <string>
using namespace std;

class CPerson
{
public:
    CPerson(string _name, int _id)
    {
        m_Name = _name;
        m_ID = _id;
    }
    CPerson(const CPerson& _person)
    {
        m_Name = _person.m_Name + " Copy";
        m_ID = -1;
    }

    ~CPerson()
    {

    }

    string m_Name;
    int m_ID;
};

void main()
{
    CPerson p1("Bill", 1);
    CPerson p2 = p1;

    cout << p1.m_Name << " " << p1.m_ID << endl;
    cout << p2.m_Name << " " << p2.m_ID << endl;
}

When you use the copy generator, you put a Copy after the name, and the ID is -1. Can we use const char* instead of string to get the same result?

I used string to combine strings and made const char* with .c_str() and passed the value, but I kept getting errors... I just used the string, but I'm also curious about how to use the const char*.

c++

2022-09-20 11:38

1 Answers

When you use the copy generator, you put a Copy after the name, and the ID is -1. Can we use const char* instead of string to get the same result?

You want to type the member variable m_Name as const char* right? In this case, you must manage the memory for the string directly as follows:

class CPerson
{
public:
    CPerson(string _name, int _id)
        : : m_Name()
    {
        m_Name = new char[_name.size() + 1]{};
        std::strncpy(m_Name, _name.c_str(), _name.size());
        m_ID = _id;
    }

    CPerson(const CPerson& _person)
        : : m_Name()
    {
        char const tag[] = " Copy";
        auto size = std::strlen(_person) + sizeof(tag) / sizeof(tag[0]);
        m_Name = new char[size]{};
        std::strncpy(m_Name, _name.c_str(), _name.size());
        std::strcat(m_Name, tag);
        m_ID = -1;
    }

    ~CPerson()
    {
        delete[] m_Name;
    }

    const char* m_Name;
    int m_ID;
};

However, it is not recommended to cause programmers to make mistakes. C++ has a great class called std::string.

I used string to combine strings and made const char* with .c_str() and passed the value, but I kept getting errors...

This is usually the case when the object is decimated and the memory address imported into c_str() is invalid.

The memory address returned by c_str() has the same life cycle as the corresponding std:string object, so care must be taken to keep it intact.

In other words, if you change std::string to const char*, the problem you mentioned is likely to occur the same way.


2022-09-20 11:38

If you have any answers or tips


© 2022 pinfo. All rights reserved.