《编码规范和测试方法——C/C++版》作业 ·002——函数返回地址、static关键词用法整理

一、函数返回地址的情形

1、函数返回值为指针

如下例中,函数func要求返回值int类型的指针,实际返回的就是数组aa[idx]的地址。

#include <iostream>

using namespace std;

int a[100] = { 0, 1, 2, 3, 4, 5, 6 };

int* func(int idx)
{
	return &a[idx];
}

int main()
{
	int* b = func(3);
	cout << b[2] << endl;  // 5

	return 0;
}

二、static关键字用法整理

1、static全局变量

在全局变量前加上static关键字,可以声明为static全局变量。

static全局变量有以下特点:

  • 在内存区中的【数据区】分配内存
  • 未初始化的static全局变量将会自动初始化为0
  • 在声明static全局变量的文件内可调用、文件外不可调用,因此在不同文件中可以取同名的static全局变量而不会冲突
  • 作用域全局范围

使用示例:

#include <iostream>

using namespace std;

static int a;


int main()
{
	cout << a << endl;  // 0

	return 0;
}

2、static局部变量

在局部变量前加上static关键字,可以声明为static局部变量。

static局部变量有以下特点:

  • 在内存区中的【数据区】分配内存
  • 未初始化的static局部变量将会自动初始化为0
  • 只在程序第一次执行到声明的时候初始化,以后不再重复执行
  • 作用域为局部作用域

使用示例:

#include <iostream>

using namespace std;

int func()
{
	static int a;  // 自动初始化为0,声明语句的初始化只执行一次
	++a;
	return 2 * a;
}

int main()
{
	cout << func() << endl;  // 2
	cout << func() << endl;  // 4
	cout << func() << endl;  // 6

	return 0;
}

3、static函数

在函数声明前加上static关键字,可以声明为static局部变量。

static函数有以下特点:

  • 在声明static函数的文件内可调用、文件外不可调用,因此在不同文件中可以取同名的static函数而不会冲突

使用示例:

static int func();

static int func()
{
	return 1;
}

4、类的static成员数据

在类的成员数据前加上static关键字,可以声明为static成员数据。

static成员数据有以下特点:

  • 在内存区中的【数据区】分配内存
  • 名字不会与全局中同名的变量名冲突
  • 可以看成是整个类的成员数据,被所有对象共有,在所有对象前保持一致
  • 既可以通过类来访问,也可以通过对象来访问
  • 和普通的成员数据一样拥有publicprotectedprivate这些访问权限修饰符
  • 需要在源文件中进行初始化(格式参考下例)

使用示例:

#include <iostream>

using namespace std;

class A
{
public:
	A() { ++num; }
	~A() { --num; }
	static int num;
};

int A::num = 0;


int main()
{
	A a1, a2;
	cout << A::num << endl;  // 2
	cout << a1.num << endl;  // 2
	{
		A a3;
		cout << A::num << endl;  // 3
		cout << a3.num << endl;  // 3
	}
	cout << A::num << endl;  // 2
	cout << a1.num << endl;  // 2

	return 0;
}

5、类的static成员函数

在类的成员函数前加上static关键字,可以声明为static成员函数。

static成员数据有以下特点:

  • 只能访问static成员数据、调用static成员函数,不能访问其他成员数据、调用其他成员函数
  • 既可以通过类来访问,也可以通过对象来访问
  • 不具有this指针
  • 不能被标记为const成员函数

使用示例:

#include <iostream>

using namespace std;

class A
{
public:
	A() { ++num; }
	~A() { --num; }
	static int getNum() { return num; }
private:
	static int num;
};

int A::num = 0;


int main()
{
	A a1, a2;
	cout << A::getNum() << endl;  // 2
	cout << a1.getNum() << endl;  // 2
	{
		A a3;
		cout << A::getNum() << endl;  // 3
		cout << a3.getNum() << endl;  // 3
	}
	cout << A::getNum() << endl;  // 2
	cout << a1.getNum() << endl;  // 2

	return 0;
}
发布了49 篇原创文章 · 获赞 9 · 访问量 3121

猜你喜欢

转载自blog.csdn.net/qq_44220418/article/details/104558617