C++ | char* 在类中实践笔记
在C++中,当类中定义有char * 变量时,在传参,构造函数,复制构造函数如何创建及赋值,来一个简单的例子就明了:
#include<iostream> #include<string> #pragma warning(disable: 4996) using namespace std; class Goods { public: Goods(); Goods(const char* _name, int _id); Goods(const Goods& goods); void Printf(); //省略.... private: char *name; int id; }; Goods::Goods(){} Goods::Goods(const char* _name, int _id) :name(new char[strlen(_name) + 1]), id(_id) { strcpy(name, _name); } Goods::Goods(const Goods& goods) : name(new char[strlen(goods.name) + 1]), id(goods.id) { strcpy(name,goods.name); } void Goods::Printf() { cout << this->id << " " << this->name << endl; } int main() { Goods goods("雪碧",1); goods.Printf(); system("pause"); }