栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++基础 面向对象

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++基础 面向对象




#include 
using namespace std;

//1.new 的基本语法
int* func() {
	//在堆区创建一个整型数据
	//new返回的是 该数据类型的指针
	int* p = new int(10);
	return p;
}

void test9() {
	int* p = func();
	cout << *p << endl;
	cout << *p << endl;
	cout << *p << endl;

	delete p;

	//cout << *p << endl;
}

//2.在堆区利用new开辟数组
void test9_2() {
	//在堆区创建10整型的数组
	int* arr = new int[10];//10代表数组有10个元素

	for (int i = 0; i < 10; i++) {
		arr[i] =( i + 1 ) * 100;//给10个元素赋值
	}

	for (int j = 0; j < 10; j ++) {
		cout << arr[j] << endl;
	}
	//释放堆区数组
	//释放数组时,要加[]才行
	delete[] arr;
}

void test9_3() {
	//引用的基本语法
	//数据类型 &别名 = 原名;
	int a = 10;
	//创建引用
	int& b = a;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	b = 100;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

}

//引用传递[与地址传递效果一致]
void mySwap03(int &a,int &b) {
	int temp = a;
	a = b;
	b = temp;
}

//引用做函数的返回值
//1.不要返回局部变量的引用[以下有误]
int& test9_4() {
	int a = 10;//局部变量存放在四区中的 栈区
	return a;
}

//2.函数调用可以作为左值
int& test9_5(){
	static int a = 10;//静态变量,存放在全局区,全局区上的数据在程序结束后系统释放
	return a;
}
//如果函数的返回值是引用,这个函数调用可以作为左值

void showValue(const int &value) {
	//value = 1000;//不可修改
	cout << "value = " << value << endl;
}

void test9_6() {
	//常量引用
	//使用场景:用来修饰形参,防止误操作。

	//int a = 10;

	//加上const之后,编译器将代码修改 int temp = 10; int & ref = temp;
	const int& ref = 10;//引用必须引一块合法的内存空间
	//ref = 20;//加入const后变为只读,不可修改

	int a = 100;
	showValue(a);
	cout << "a = " << a << endl;

}



int main9() {
	
	//test9();
	//test9_2();
	//test9_3();
	test9_6();

	system("pause");

	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1009216.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号