C++基础知识(常函数)

常函数:

       形式: void fun() const {;}

      构造函数和析构函数不可以是常函数

      特点:①可以使用数据成员,不能进行修改,对函数的功能有更明确的限定;

                 ②常函数只能调用常函数,不能调用普通函数;

                ③常函数的this指针是const CStu*.

#include<iostream>
using namespace std;

class CStu
{
public:
	int a;
	CStu()
	{
		a = 12;
	}

	void Show() const
	{
		//a = 13; //常函数不能修改数据成员
		cout <<a << "I am show()" << endl;
	}
};

int main()
{
	CStu st;
	st.Show();
	system("pause");
	return 0;
}

静态成员函数:

       无this;

       不能调用普通成员变量,可以调用静态成员变量;

      可以作为一种指挥该类所有对象的作用;

       属于类的属性,不是对象,即所有对象共有一个(可以通过类名调用或者通过对象调用) 

扫描二维码关注公众号,回复: 3512122 查看本文章

不使用for循环进行累加

#include<iostream>
using namespace std;

class CStu
{
public:
	static int b;

	CStu()
	{
		b++;
	}
};

int CStu::b = 0;

int main()
{
	CStu st[5];
	cout << CStu::b << endl;
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_37753215/article/details/81873341