内联函数:在编译时将函数体嵌入在每一个调用处。
优点:效率高
省去了图中2(调用),4(返回)这两步
内联函数必须是比较少,结构清晰的函数。
如果是比较复杂的代码,就算加上inline的关键字,也不会当作内联函数。
构造函数:
拷贝构造函数:
这里用的const是为了不让这个函数修改这个参数
构造函数总结:
析构函数:
#pragma once
#include <string>
using namespace std;
class Teacher
{
private:
const int m_iStuNum;
string m_strName;
int m_iAge;
char* m_pFirstName;
public:
//Teacher(void);
Teacher(string name = "xd" , int age = 18);//不可以和无参构造函数共存
Teacher(const Teacher& t);
string getName();
void setName(string name);
int getAge();
void setAge(int age);
int getStuNum();
~Teacher(void);
};
#include "Teacher.h"
#include <iostream>
using namespace std;
//Teacher::Teacher(void):m_strName("xxf"), m_iAge(22)
//{
// cout << "无参构造函数" << endl;
//}
Teacher::Teacher(string name, int age):m_strName(name), m_iAge(age), m_iStuNum(50){
//this->m_iStuNum = 200; 这样修改const变量是错误的
m_pFirstName = new char[20];
cout << "有默认参数构造函数" << endl;
}
Teacher::Teacher(const Teacher& t):m_iStuNum(50){//这个const的成员变量一定要初始化,不然编译不过
this->m_iAge = t.m_iAge;
this->m_strName = t.m_strName;
cout << "拷贝构造函数" << endl;
}
int Teacher::getStuNum(){
return this->m_iStuNum;
}
Teacher::~Teacher(void)
{
cout << "析构函数" << endl;
delete m_pFirstName;
m_pFirstName = NULL;
}
int Teacher::getAge(){
return m_iAge;
}
void Teacher::setAge(int age){
this->m_iAge = age;
}
string Teacher::getName(){
return m_strName;
}
void Teacher::setName(string name){
this->m_strName = name;
}
#include <iostream>
#include <string>
#include "Teacher.h"
using namespace std;
int main()
{
Teacher *t1 = new Teacher();
Teacher *t2 = new Teacher("hqq", 20);
Teacher *t3 = new Teacher("zl");
Teacher *t4 = new Teacher(*t1);
Teacher *t5 = t4;
cout << t1->getName() << "--" << t1->getAge() << endl;
cout << t2->getName() << "--" << t2->getAge() << endl;
cout << t3->getName() << "--" << t3->getAge() << endl;
cout << t4->getName() << "--" << t4->getAge() << endl;
cout << t4->getStuNum() << endl;
cout << t5->getName() << "--" << t5->getAge() << endl;
cout << t5->getStuNum() << endl;
//delete t5; 4 和 5指向同一个内存,就会出现空地址指针
cout << t1 << endl;
cout << t4 << endl;
cout << t5 << endl;
delete t1;
delete t2;
delete t3;
system("pause");
return 0;
}
总结: