c++ 封装 (上)


内联函数:在编译时将函数体嵌入在每一个调用处。

优点:效率高

省去了图中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;
}



总结:










  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值