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();
}