C++学习札记:第31课 类的成员函数

1.类的普通成员函数:
跟普通的函数没什么太大的区别,
唯一的区别就是必须由该类的实例化对象去调用

2.inline 内联函数
inline内联函数是从C语言的发展而来的。
与普通函数调用的区别是函数调用的压栈、出栈等开销。所以执行效率方面要比函数高。
inline使用原则:函数比较短小精悍,执行体比较小,而且经常被调用。

#include "pch.h"
#include <iostream>
using namespace std;

#define MAX_NUM( x, y) (x>y?x:y)                        //这个就是定义的一个宏

int main()
{
	int max = MAX_NUM(4, 3);
	cout << max << endl;
}
#include "pch.h"
#include <iostream>
using namespace std;

class CStudent
{
private:
	char sex;
	inline int MAX_NUM(int x, int y)                     //这儿即定义了一个内联函数
	{
		x > y ? x : y;
	}
public:
	string name;
	int age;
	int num;
	int Max(int a, int b, int c)
	{
		MAX_NUM(a, b) > c ? MAX_NUM(a,b) : c;
	}
	void print_name()
	{
		cout << "name=" << name << endl;
	}
};

int main()
{
 
}

Attention:默认情况下,在类体中直接定义/实现的函数,C++会自动的将其作为inline内联函数来处理

3.类的声明和实现分离:
普通的定义是这样子的,类的声明和实现都写在一起,层次很不清晰:

class CStudent
{
private:
	char sex;
	inline int MAX_NUM(int x, int y)
	{
		x > y ? x : y;
	}
public:
	string name;
	int age;
	int num;
	int Max(int a, int b, int c)
	{
		MAX_NUM(a, b) > c ? MAX_NUM(a,b) : c;
	}
	void print_age()
	{
		cout << "age=" << age << endl;
	}
};

好的做法就是将类的声明和成员函数的定义分离开,成员函数的声明放在类的内部,实现或者定义放在类的外部,加上作用域限定一下就行,改写如下:

#include "pch.h"
#include <iostream>
using namespace std;

class CStudent                          //相当于给类的声明瘦了身,把成员函数拿到类的声明外部去了,看起来比较简洁。
{
private:
	char sex;
	inline int MAX_NUM(int x, int y);
public:
	string name;
	int age;
	int num;
	int Max(int a, int b, int c);
	void print_age();
};

//以下是class中成员函数的外部定义(注意格式的书写,要加“类名::”)
inline int  CStudent::MAX_NUM(int x, int y)          //但要注意加作用域::
{
	return x > y ? x : y;
}

int CStudent:: Max(int a, int b, int c)
{
	return MAX_NUM(a, b) > c ? MAX_NUM(a, b) : c;
}

void CStudent::print_age()
{
	cout << "age=" << age << endl;
}

int main()
{
 
}

4.使用多文件分离类的声明和实现
将**类的声明放到 .h 头文件中,将类的实现放到 .cpp 实现文件中**,谁要使用这个类,就 include 包含 .h 类的头文件就可以了。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

#pragma once
#include"pch.h"
#include<iostream>
using namespace std;

class CStudent
{
private:
	char sex;
	inline int MAX_NUM(int x, int y);
public:
	string name;
	int age;
	int num;
	int Max(int a, int b, int c);
	void print_age();
};

在这里插入图片描述

#include "pch.h"
#include "CStudent.h"

inline int  CStudent::MAX_NUM(int x, int y)
{
	return x > y ? x : y;
}

int CStudent::Max(int a, int b, int c)
{
	return MAX_NUM(a, b) > c ? MAX_NUM(a, b) : c;
}

void CStudent::print_age()
{
	cout << "age=" << age << endl;
}

在这里插入图片描述

#include "pch.h"
#include"CStudent.h"

int main()
{
	CStudent stu;
	stu.age = 15;
	stu.print_age();
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值