c++ static/inline/friend

static:包含静态成员和静态函数

静态成员:属于类,所有对象共享。可以理解为在当前类下的一个全局变量

#include <iostream>

using namespace std;

class Student {
public:
	Student(int val){
		num ++;
	}
	~Student(){
		
	}
	static int num;       //静态成员(声明)
private:
	int age ;
	int score;
};

int Student::num = 0;     //定义

int main()
{
	Student tom(100);
	cout << tom.num << endl;

	Student jack(200);
	cout << jack.num << endl;

	cout << Student::num << endl;

	system("pause");
	return 0;
}

 

 静态函数:只能访问静态成员和其他静态函数。限制该函数只能在本文件使用

#include <iostream>

using namespace std;

class Student {
public:
	Student(int val){
		num ++;
	}
	~Student(){
		
	}
	static int num;
	static void function(){
		num += 10;
	}
private:
	int age ;
	int score;
};

int Student::num = 0;

int main()
{
	Student tom(100);
	Student::function();//调用
	cout << Student::num << endl;//11
	tom.function();//调用
	cout << Student::num << endl;//12
	system("pause");
	return 0;
}

inline(内联函数)就是将一简单的函数进行调用时进行更改,方便执行

friend        友元函数 :提供访问私有成员的一个接口

#include <iostream>

using namespace std;

class Student{
public:
    friend void function(Student &s);//声明
    friend class Base;  //声明
private:
    int age;
    int score;
}; 

void function(Student &s)//友元函数
{
    s.age = 10;
    cout << s.age <<endl;
}

class Base{         //友元类
public:
    void show(){
       cout << s.age <<endl; 
    }
private:
    Student s;
};

int main()
{
    Student tom;
    function(tom);
    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值