請(qǐng)問有誰知道這樣寫為什么不行:把無參構(gòu)造函數(shù)和有參構(gòu)造函數(shù)放在類外定義。如下代碼
class Student
{
?public:
? ?Student()
? Student(string _name);
? ?Student(const Student& stu){};
? ?~Student(){};
? ?void setName(string _name);
? ?string getName();??
? ?
?private:
?string m_strName;
};
void Student::Student()
{
? ? ? ?m_strName=" ";
? ?}
void Student::Student(string _name)
? ?{
? ? m_strName=_name;
? ?}
void Student::setName(string _name)
{
? ? m_strName=_name;
}
string Student::getName()
{
? ? return m_strName;
}
int main(void)
{
? ? // 通過new方式實(shí)例化對(duì)象*stu
? ? Student *stu = new Student();
? ? // 更改對(duì)象的數(shù)據(jù)成員為“慕課網(wǎng)”
stu->setName("慕課網(wǎng)"); // 打印對(duì)象的數(shù)據(jù)成員
cout<<stu->getName()<<endl;
delete stu;
stu=NULL;
return 0;
}
2019-03-06
lass Student
{
?public:
? ?Student(); //?在聲明類的時(shí)候Student()后面沒有;
? Student(string _name);
? ?Student(const Student& stu);? //?你這里是拷貝構(gòu)造函數(shù)的聲明,已經(jīng)在類外定義的不需要函數(shù)體, 去掉大括號(hào),?
? ?~Student(){};
? ?void setName(string _name);
? ?string getName();??
? ?
?private:
?string m_strName;
};
##### 其他參考其他
2019-03-03
無參構(gòu)造函數(shù)和有參構(gòu)造函數(shù)放在類外定義沒有返回值,所以去掉void即可。ps:在定義類的時(shí)候Student()后面沒有;
2019-01-30
無參構(gòu)造函數(shù)和有參構(gòu)造函數(shù)在定義時(shí)都沒有返回值,在你定義的兩個(gè)構(gòu)造函數(shù)的頭部應(yīng)去掉void,并且,在類定義中,你的無參構(gòu)造函數(shù)聲明Student()后面沒有加上分號(hào)
2019-01-09
無參構(gòu)造函數(shù)和有參構(gòu)造函數(shù)放在類外定義沒有返回值,所以去掉void即可。ps:在定義類的時(shí)候Student()后面沒有;