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。
不可更改:一旦引用被初始化为某个变量的别名,就不能再改变指向其他变量。
透明使用:使用引用时,语法上看起来就像是直接操作原始变量,这使得代码更加直观。