内联函数
内联函数是一个函数,内联函数的作用是将函数展开,将函数的调用过程转换为直接间函数内部的代码在调用出展开。内联函数的定义和声明需要在同一个文件中,若内联函数的声明和定义在不同的文件中,那么在编译的时候,内联函数找不到其要展开的内容从而报错。
使用inline修饰的方法,不一定能够成为内联的,只是给编译器一个建议,由编译器来判断最终是否内联。
友元函数
友元函数的作用是来打破类的封装,在类中声明的友元函数,可以访问内中的所有成员。下面的代码是一个类的声明,从类的声明中可以看到,数据成员都是私有成员,在其中定义了一个内联函数,一个友元函数。
这是一个头文件
#pragma once
#include<stdio.h>
class Rect
{
private:
int pos_x;
int pos_y;
int width;
int height;
public :
Rect();
Rect(int x, int y);
inline void show_info();
friend void get_posx(int *x, int *y);
};
void Rect::show_info()
{
printf("pos_x = %d; pos_y = %d; width = %d; height = %d\n", pos_x, pos_x, width, height);
}
这是类函数的实现
#include "Rect.h"
Rect::Rect()
{
pos_x = 0;
pos_y = 0;
width = 100;
height = 100;
}
Rect::Rect(int x, int y)
{
pos_x = x;
pos_y = y;
}
这是主函数
#include<iostream>
#include"Rect.h"
void get_posx(int *x, int *y)
{
Rect R1(10,10);
*x = R1.pos_x;
*y = R1.pos_y;
}
int main()
{
int x;
int y;
Rect R1;
get_posx(&x, &y);
printf("x is %d;y is %d\n", x, y);
R1.show_info();
getchar();
return 0;
}
在main函数中,实现了友元函数的的定义,可以看到有缘函数中,直接访问到了类中的私有成员pos_x和pos_y;最终的执行结果如下:
类中的常量成员
类中的常量成员通常用来存储一些信息,对类中的常量成员的赋值方式由两种,一种是通过在定义时直接赋值的方式完成,一种是在构造是使用初始化列表来对常量成员进行初始化。
对于在定义时就初始化这种情况,在类产生对象时,每个对象的该成员的值都是一样的。在实际情况中,并不希望每个对象他们的常量成员都是相同的,因此第二种方法,使用的频率更高。
使用构造,在初始化列表中对常量成员进行赋值,在C++ 中是被允许的。
#pragma once
#include<stdio.h>
class Rect
{
private:
int pos_x;
int pos_y;
int width;
int height;
public :
//类中的常量成员
const int const_info;
//在构造函数的参数中,给出要赋值给常量成员的值
Rect(int _info);
Rect(int x, int y, int _info);
inline void show_info();
friend void get_posx(int *x, int *y);
};
void Rect::show_info()
{
printf("pos_x = %d; pos_y = %d; width = %d; height = %d\n", pos_x, pos_x, width, height);
}
#include "Rect.h"
//在构造函数内容之前,使用初始化列表对常量成员进行赋值
//对于常量成员的赋值方式,类似于C++中新建一个对象时的重载后的赋初始值的方式
Rect::Rect(int _info):const_info(_info)
{
pos_x = 0;
pos_y = 0;
width = 100;
height = 100;
}
Rect::Rect(int x, int y, int _info) :const_info(_info)
{
pos_x = x;
pos_y = y;
}