lv19 C++开发前言 1

1 C++/QT 图形界面编程

2 C++语法升级

四大升级:引用 、默认参数 、函数重载 、堆内存

引用——示例:

#include <stdio.h>

/*
int swap(int a, int b)  //错误方式
{
	a ^= b;
	b ^= a;
	a ^= b;
}
*/
/*
void swap(int *p, int *q) //C方式
{
	*p ^= *q;
	*q ^= *p;
	*p ^= *q;
}
*/
int swap(int &a, int &b) //C++方式
{
	a ^= b;
	b ^= a;
	a ^= b;
}
int main()
{
	int a = 100;
	int b = 10;

	printf("a = %d, b = %d\n", a, b);
//	swap(&a, &b);
	swap(a, b);
	printf("a = %d, b = %d\n", a, b);
}

默认参数——示例

#include <stdio.h>

//void sortarr(int *arr, int len, int flag=UP);
void debug(const char *ptr = "---------------")
{
	printf("%s\n", ptr);
}

int main()
{
	debug();
	debug();
	debug();
	debug();
	debug();
	debug();
	debug("hello");
	debug("world");
}

函数重载——示例

#include <stdio.h>
#include <string.h>

/*
int intcmp(int a, int b)
{
	return a-b;
}

int scmp(const char *str1, const char *str2)
{
	return strcmp(str1, str2);
}
*/
int cmp(int a, int b)
{
	return a-b;
}

int cmp(const char *str1, const char *str2)
{
	return strcmp(str1, str2);
}
int main()
{
	printf("%d\n", cmp(1, 2));
	printf("%d\n", cmp("aaaaaa", "bbbb"));
}

堆内存——示例

#include <stdio.h>
#include <malloc.h>
#include <string.h>

int main()
{
/*
	char *p = (char *)malloc(10);
	strcpy(p, "hello");

	printf("p: %s\n", p);

	free(p);
*/


	int *intp = new int;//(int*)malloc(sizeof(int));

	*intp = 100;

	printf("*intp = %d\n", *intp);

	delete intp;
/
	char *p = new char[10];

	strcpy(p, "hello");

	printf("p: %s\n", p);

	delete [] p;
	
}

3 概念升级

名字空间: namespace NAME1{ }
类 class :
	class  A{
	public:
	private:
	};
面向对象编程(OOP): 
	类、对象、封装,继承、组合等

示例

#include <stdio.h>

namespace A{

	int add(int a, int b)
	{
		return a+b;
	}
};

namespace B{

	int add(int a, int b)
	{
		return 2*a+b;
	}
};

using namespace A;

int main()
{
	printf("%d\n", A::add(1, 2) );
	printf("%d\n", B::add(1, 2) );
	printf("%d\n", add(1, 2) );
}

//执行结果
3
4
3

4 思维升级

5 习题

请描述C++中的引用的作用及使用特点(可以举例说明)。

引用的主要作用是作为原始数据的一个别名来使用,这样可以在不复制实际数据的情况下操作原始数据,从而提高程序的效率和灵活性。

直接访问:引用允许程序直接访问被引用变量的值,而不需要通过指针解引用。
不可空:引用在定义时必须初始化,并且不能像指针那样指向nullptr。
不可更改:一旦引用被初始化为某个变量的别名,就不能再改变指向其他变量。
透明使用:使用引用时,语法上看起来就像是直接操作原始变量,这使得代码更加直观。

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

4IOT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值