简单复习了一下C++的构造函数,其中注意函数重载与函数默认值设置,不要出现冲突。
关于C++的构造函数,
0.在对象实例化的时候默认进行调用(有且仅有一次)
1.构造函数没有返回值
2.构造函数的名字必须和类(class)的名字相同
3.系统会默认添加一个为空的构造函数
4.可以自行添加含有参数的构造函数
5.构造函数可以进行重载
Teacher.h
#include<iostream>
#include<algorithm>
using namespace std;
class Teacher
{
public:
Teacher();
Teacher( string name,int age =38);
void set_strName( string name );
string get_strName();
void set_iAge( int age );
int get_iAge();
private:
string m_strName;
int m_iAge;
};
Teacher.cpp
#include<iostream>
#include<string>
#include"TEACHER.h"
using namespace std;
Teacher::Teacher()
{
m_strName = "hello";
m_iAge = 5;
cout << "Teacher() output" << endl;
}
Teacher::Teacher(string name,int age )
{
m_strName = name;
m_iAge = age;
cout << "Teacher( string name,int age ) output" << endl;
}
void Teacher::set_strName(string name){
m_strName = name;
}
string Teacher::get_strName(){
return m_strName;
}
void Teacher::set_iAge(int age){
m_iAge = age;
}
int Teacher::get_iAge(){
return m_iAge;
}
int main()
{
Teacher t1;
Teacher t2("xiaoming",10);
Teacher t3("JIM");
cout << t1.get_strName() << " " << t2.get_iAge() << " " << endl;
cout << t2.get_strName() << " " << t2.get_iAge() << " " << endl;
cout << t3.get_strName() << " " << t3.get_iAge() << " " << endl;
return 0;
}