1. 程式人生 > >建構函式與類外定義

建構函式與類外定義

簡單複習了一下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; }