重拾C++

550 阅读2分钟

前言

简单快速地过一遍c++的基本概念。

1.1 IO

输入/输出优先使用进行输入/输出操作。

#include <iostream>
//C语言风格的IO库为<cstdio>
int main (int argc, char **argv)
{
    int i;
    std::cout << "Please enter an integer value: ";
    std::cin >> i;
    std::cout << "The value you entered is " << i  << std::endl;
    return 0;
}

1.2 内存管理

使用newdelete代替mallocfree

delete做两件事:调用析构函数并释放内存。它只能删除指针❗❗❗❗

#include<iostream>

int main() {
	int* a = new int;
	*a = 100;
	delete a;//释放指针*a指向的空间
	int* b = new int[5];
	for (int i = 0; i <= 4; i++) {
		b[i] = i;
	}
	delete[] b;//释放指针*b所指向的内存空间,

}

1.3 引用

引用相当于为变量创建一个别名(alias),只要该变量还存在,就可以使用别名代替该变量。

#include<iostream>
int main(int argc,char **argv) {
	int x;
	int& foo = x;
	foo = 42;
	std::cout << "&x= " << &x << " x=" << x << std::endl;
	std::cout << "&foo= " << &foo << " foo=" << foo << std::endl;
}

1.4 默认参数

#include<iostream>
float foo(float a = 0, float b = 1, float c = 2)
{
	return a + b + c;
}


int main(int argc, char** argv) {
	std::cout << foo(1) << std::endl
		<< foo(1, 2) << std::endl
		<< foo(1, 2, 3) << std::endl;//4,5,6
}

1.5 命名空间

命名空间允许将类,函数和变量归为通用作用域名称,可在其他位置使用。

可以防止同名变量冲突

#include<iostream>
namespace first { int var = 5; }
namespace second { int var = 3; }

int main(int argc, char** argv) {
	std::cout << first::var << std::endl << second::var << std::endl;//5,3
}


1.6 重载

函数重载是指可以使用相同名称创建多个函数,只要它们具有不同的参数(类型不同或数量不同或类型、数量皆不相同)。

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

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

1.7 常量与内联

C语言中,通常使用#define来定义常量以及宏。但是容易出错

#define SQUARE(x) x*x
int result = SQUARE(3+3);//出错。结果为3+3*3+3=15

C++中使用const表示常量

 const int two = 2;

对于宏,最好使用内联表示法

int inline square(int x)
{
    return x*x;
}

1.8 C与C++混编

#ifdef __cplusplus
extern "C" {
#endif

#include "some-c-code.h"

#ifdef __cplusplus
}
#endif