cpp笔记01-基础知识

这篇博客详细介绍了C++的基础知识,包括命名空间、字面量、变量、运算符、枚举类型、结构体、条件语句、循环、字符串、面向对象等核心概念。还讨论了指针、动态内存、常量、引用、类型别名等特性,以及C++中的异常处理和类型推断。
摘要由CSDN通过智能技术生成

命名空间 namespace

命名空间解决了不同代码段之间的命名冲突问题。将函数定义在命名空间之下,使用时通过::(scope resolution operator)调用,或 using 指令引入。using 可以只引入命名空间下的一个函数。
一个文件可以包含多个 using,但是需要注意过度使用导致互相影响。
不要在 header file 中使用 using,导致全局引入,尽量在小的范围内引入。

namespace mycode {
   
	void foo() {
   
		std::cout << "foo() called in the mycode namespace" << std::endl;
	}
}

// 1. scope resolution operator
mycode::foo(); // Calls the "foo" function in the "mycode" namespace

// 2. using directive
using namespace mycode;
foo(); // Implies mycode::foo();

// 3. refer to a particular item within a namespace
using std::cout;
cout << "Hello, World!" << std::endl;

命名空间可以嵌套定义。

namespace MyLibraries {
   
	namespace Networking {
   
		namespace FTP {
   
			/* ... */
		}
	}
}

// c++ 17 syntax
namespace MyLibraries::Networking::FTP {
   
	/* ... */
}

命名空间可以定义别名

namespace MyFTP = MyLibraries::Networking::FTP;

字面量 literals

标准字面量,用于在代码中写入数字和字母

  • Decimal literal, 123
  • Octal literal, 0173
  • Hexadecimal literal, 0x7B
  • Binary literal, 0b1111011
  • floating-point value (such as 3.14f)
  • double floating-point value (such as 3.14)
  • hexadecimal floating-point literal (such as 0x3.ABCp-10 and 0Xb.cp12l)
  • single character (such as ‘a’)
  • zero-terminated array of characters (such as “character array”)

也支持自定义的字面量类型

变量 variables

代码中的任何地方都可以定义变量,定义后的变量在当前block中都可以使用。定义变量可以不初始化值,这样很容易引入bug,编译器一般会有检查。

int uninitializedInt;
// C++11 uniform initialization syntax(recommended)
int initializedInt {
    7 };
cout << format("{} is a random value", uninitializedInt) << endl;
cout << format("{} was assigned an initial value", initializedInt) << endl;
// assignment initialization syntax
int initializedInt = 7;

c++ 是强类型的,变量都需要有类型

  • (signed) int / signed
  • (signed) short (int)
  • (signed) long (int)
  • (signed) long long (int)
  • unsigned (int)
  • unsigned short (int)
  • unsigned long (int)
  • unsigned long long (int)
  • float
  • double
  • long double
  • char
  • unsigned char
  • signed char
  • char8_t (since C++20)
  • char16_t (since C++20)
  • char32_t (since C++20)
  • wchar_t
  • bool

string 以类库的形式提供

数字的最大最小值推荐 使用 std::numeric_limits

cout << "int:\n";
cout << format("Max int value: {}\n", numeric_limits<int>::max());
cout << format("Min int value: {}\n", numeric_limits<int>::min());
cout << format("Lowest int value: {}\n", numeric_limits<int>::lowest());
cout << "\ndouble:\n";
cout << format("Max double value: {}\n", numeric_limits<double>::max());
cout << format("Min double value: {}\n", numeric_limits<double>::min());
cout << format("Lowest double value: {}\n", numeric_limits<double>::lowest());

变量可以初始化为对应类型的0值

float myFloat {
   };
int myInt {
   };

变量可以使用cast转化为另一种类型

float myFloat {
    3.14f };
int i1 {
    (int)myFloat };
int i2 {
    int(myFloat) };
int i3 {
    static_cast<int>(myFloat) };

使用浮点数计算会丢失精度

特殊的浮点数

  • +/-infinity 无限大/无限小
  • NaN 不是一个数字,例如除以0,未定义的结果

运算符 operators

三种类型的运算符

  • unary 一个表达式的计算
  • binary 两个表达式的计算
  • ternary 三个表达式的计算

运算符(优先级从低到高)

++ -- (postfix)
! ++ -- (prefix)
*/ %
+ -
<< >>
&
^
|
= += -= *= /= %= &= |= ^= <<= >>=

例子

int someInteger {
    256 }; short someShort;
long someLong;
float someFloat;
double someDouble;

someInteger++;
someInteger *= 2;
someShort = static_cast<short>(someInteger);
someLong = someShort * 10000;
someFloat = someLong + 0.785f;
someDouble = static_cast<double>(someFloat) / 100000;
cout << someDouble << endl;

枚举类型 enumerated types

枚举定义一个变量的取值范围

enum class PieceType {
   
	King,
	Queen,
	Rook,
	Pawn
};
PieceType piece {
    PieceType::King };

enum class State {
    Unknown, Started, Finished };
enum class Error {
    None, BadInput, DiskFull, Unknown};

// c++ 20 using enum declaration
using enum PieceType;
PieceType piece {
    King };

// old style
enum PieceType {
    PieceTypeKing, PieceTypeQueen, PieceTypeRook, PieceTypePawn };
PieceType myPiece {
    PieceTypeQueen };

结构体 structs

使用结构体可以把一个或多个类型封装成一个新类型
c++20支持定义模块,模块接口文件的扩展名通常为.cppm,可以使用 export 关键字导出,以方便外部使用

employee.cppm

export module employee;

export struct Employee {
   
	char firstInitial;
	char lastInitial;
	int employeeNumber;
	int salary;
};

main.cpp

import <iostream>;
import <format>;
import employee;

using namespace std;

int main() {
   
	// Create and populate an employee.
	Employee anEmployee;
	anEmployee.firstInitial = 'J';
	anEmployee.lastInitial = 'D';
	anEmployee.employeeNumber = 42;
	anEmployee.salary = 80000;
	
	// Output the values of an employee.
	cout << format("Employee: {}{}", anEmployee.firstInitial, anEmployee.lastInitial) << endl;
	cout << format("Number: {}", anEmployee.employeeNumber) << endl;
	cout << format("Salary: ${}", anEmployee.salary) << endl;
}

条件语句 conditional statements

if/else Statements

if (<initializer>; <conditional_expression>) {
   
	<if_body>
} else if (<else_if_expression>) {
   
	<else_if_body>
} else {
   
	<else_body>
}

switch Statements

switch (<initializer>; <expression>) {
   
	<body>
}

enum class Mode {
    Default, Custom, Standard };

int value {
    42 };
Mode mode {
    /* ... */ };
switch (mode) {
   
	using enum Mode;
	case Custom:
		value = 84;
	case Standard:
	case Default:
		// Do something with value ...
		break;
}

条件运算符 conditional operators

三元运算符,简单的实现if

if [something] then [perform action], otherwise [perform some other action].

cout << ((i > 2) ? "yes" : "no");

逻辑运算符 logical evaluation operators

<  <=  >  >=
==
!=
<=>
!
&&
||

三向比较符 three-way comparisons

三向比较运算符可用于确定两个值的顺序。它也被称为太空飞船操作员&#

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值