问题
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:
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.
来源:https://stackoverflow.com/questions/23441919/dynamically-allocate-memory-to-a-char-pointer