动态地将内存分配给字符指针 [英] Dynamically allocate memory to a char-pointer
问题描述
这是正确的代码还是应该动态地分配内存给接收char指针的String类的成员变量?
#include< iostream>
using namespace std;
class String {
char * string;
public:
String(char * ch){
string = ch;
}
void print(){
cout<串;
}
};
int main(){
String string(hello);
string.print();
return 0;
}
让开始语句
字符串字符串(hello);
这里hello是一个字符串文字。用作参数时,将隐式转换为
类型的对象const char *
因此,类的相应数据成员应定义为
const char * string;
结果类应该定义为
class String
{
private:
const char * string;
public:
String(const char * ch):string(ch)
{
}
void print
cout<<串;
}
};
由于字符串文字具有静态存储持续时间,因此您的代码有效。考虑到类不拥有指针。
另一方面,如果你想让类确实拥有指针,那么你需要动态分配一个构造函数参数指向的数据。在这种情况下,您还需要至少明确定义复制构造函数,复制赋值运算符和析构函数。
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;
}
解决方案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.
这篇关于动态地将内存分配给字符指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!