Dynamically allocate memory to a char-pointer [clo

2019-08-20 16:05发布

Is this correct code or should I dynamically allocate memory to the member-variable of the String-class that receives the char-pointer?

#include <iostream>
using namespace std;

class String {
    char *string;
public:
    String(char *ch) {
    string = ch;
}

void print() {
    cout << string;
}

};

int main() {

   String string("hello");
   string.print();

return 0;

}

1条回答
戒情不戒烟
2楼-- · 2019-08-20 16:40

Let start from statement

String string("hello");

Here "hello" is a string literal. Used as an argument it is implicitly converted to an object of type

const char *

So the corresponding data member of the class should be defined as

const char *string;

And as the result the class should be defined as

class String 
{
private:
    const char *string;
public:
    String( const char *ch ) : string( ch )
    {
    }

    void print() const 
    {
        cout << string;
    }
};

As string literals have static storage duration then your code is valid. Take into account that the class does not possess the pointer.

On the other hand if you want that the class indeed possesses the pointer then you need dynamically allocate a copy of the data pointed to by the constructor argument. In this case you need also explicitly define at least the copy constructor, copy assignment operator, and destructor.

查看更多
登录 后发表回答