构造函数与类外定义

简单复习了一下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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值