C++关于构造方法中给char *型赋值的问题

来源:百度知道 编辑:UC知道 时间:2024/06/10 13:21:44
class Student
{
public:
Student(char *name = "qwe", int stature = 180, int avoirdupois = 75);
Student(const Student &stu);
public:
~Student(void);
private:
char * m_name;
int m_stature, m_avoirdupois;
};
Student::Student(char *name, int stature, int avoirdupois)
{
this->m_name = new char[sizeof(name)];
*(this->m_name) = *name;
this->m_stature = stature;
this->m_avoirdupois = avoirdupois;
cout << "缺省构造函数" << endl;
cout << "姓名:" << *(this->m_name) <<",身高:" << this->m_stature << ",体重:" << this->m_avoirdupois << endl;
}为什么打印出来只有一个字符q?

字符串长度不能用sizeof()求!要用
m_name = new char[strlen(name) + 1];
//需要#include <string.h>

*(this->m_name) = *name;
//字符串的拷贝不能这样,需要把所有字符都拷出来!
strcpy(m_name, name);

//需要#include <string.h>

打字符串不要取内容,直接传指针
cout << "姓名:" << m_name);

不能这么构造。
m_name = new char[ strlen(name)+1];
strcpy( m_name,name);

这里拥sizeof得到的是字符指针的大小,二不是字符串长度。

复制也不对哦。。