class Cperson
{
private:
int m_age;
float m_height;
char* m_name;
public:
Cperson(int age,float height,const char* name)
{
m_age=age;
m_height=height;
if(m_name)//先判断当前是否为空
delete[] m_name;
if(name)//如果外部传入的不为空
{
int len=strlen(name);
m_name=new char[len+1];//创建内存
strcpy(t m_name,name);
}
else
m_name=nullptr;
}
}
class Cperson
{
private:
int m_age;
float m_height;
char* m_name;
public:
void setPerson(int age,float height,const char* name)
{
m_age=age;
m_height=height;
if(m_name)//先判断当前是否为空
delete[] m_name;
if(name)//如果外部传入的不为空
{
int len=strlen(name);
m_name=new char[len+1];//创建内存
strcpy(t m_name,name);
}
else
m_name=nullptr;
}
}
class Cperson
{
private:
int m_age;
float m_height;
char* m_name;
public:
Cperson(int age,float height,const char* name);
}
//m_name为指针类型,需要自己申请空间
Cperson::Cperson(int age,float height,const char* name):m_age(age),m_height(height)
{
if(m_name)//先判断当前是否为空
delete[] m_name;
if(name)//如果外部传入的不为空
{
int len=strlen(name);
m_name=new char[len+1];//创建内存
strcpy(m_name,name);
}
else
m_name=nullptr;
}
class Cperson
{
private:
int m_age;
float m_height;
public:
Cperson(int age,float height);
}
Cperson::Cperson(int age,float height):m_height(height),m_age(age)
{}
错误事例(初始化顺序导致的错误)
//下面代码中,i先被初始化,但是i是根据j初始化的,但j后初始化,就会产生不好的后果
class X
{
int i;
int j;
public:
X(int value):j(value),i(j)
{}
};
class X
{
int i;
int j;
public:
//j先初始化,i再初始化
X(int value):j(value)
{
i(j);
}
};
class Person
{
private:
const int id;
int& m_id;
public:
Person(int i);
};
Person::Person(int i)
{
id=i;//错误,const成员变量必须在成员初始化列表初始化
m_id=id;//错误,引用也必须在成员初始化列表初始化
}
class Word{
string _name;
int _cnt;
public:
Word(){
_name=0;//先创建一个临时string对象,赋值为0,然后拷贝给_name
_cnt=0;
//构造函数结束之后,临时对象析构释放
}
};
class Word{
string _name;
int _cnt;
public:
Word():_name(0),_cnt(0){} //直接初始化_name,不创建临时对象
};