---
title: "C++ 学习笔记（基础篇）"
author: "lvmy"
date: "2012-08-20T14:50:11Z"
tags: ["C++", "笔记"]
categories: ["编程语言"]
slug: "c"
draft: false
lastmod: "2012-08-20T18:25:44Z"
id: 1638411
url: "https://lvmy.iteye.com/blog/1638411"
---

**第一章：初识C++**

 

1、C++的“预处理符”、“头文件”、“命名空间”、“输入输出语句”：

 

 

```
#include <iostream>

using namespace std;
//using std::cout;
//using std::cin;

int main(){
    int x;
    cout<<"请输入一个数字：";
    cin>>x;
    cout<<x;

    return 0;
}
```

 

2、函数的声明与定义：

 

 

```
#include <iostream>

using namespace std;

//良好的C＋＋代码编写习惯要先声明函数再定义。
void test_func(char );    //函数的声明

int main(){
    test_func("测试输出。");
}

void test_func(char para){    //函数的定义
    cout<<para;
}

```

 

 

3、C++基本数据类型

 

 

```
#include <iostream>
#include <iomanip>

int main(){
    
	bool bl = true;			//布尔型 true（1）、false（0）
	cout<<bl;

	char ch = 'A';			//字符型，单字节字符用单引号，多字节用双引号
	cout<<ch;

	setlocale(LC_ALL, "chs");
	wchar_t wt[] = L"汉";			//双字节型
	cout<<wt;


	int a;			//整型
	short b;			//短整型
	long c;			//长整型

	unsigned int sa;			//无符号的整型变量
	unsigned short int sb;			//无符号的短整型变量
	unsigned long int sc;			//无符号的长整型变量

	float ft = 12.3456789012345;			//单精度浮点型
	cout<<setprecision(15)<<ft;			//单精度只能保持6到7位的精准度

	double dl = 12.3456789012345;			//双精度浮点型,可保持15到16位的精准度

	//常量const
	const double PI = 3.141592653;

	//枚举型常量enum，可以用文字来替代数字，使程序更加易懂
	enum num{zero, one, two, three, four};			//定义枚举类型变量
	enum day{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
	day today; 
	today = Monday;
	if (today == Sunday || today == Saturday){
		cout<<"周末休息\n";
	}else{
		cout<<"工作日\n";
	}

	return 0;
}
```

 

 

 

4、二进制的补码

 

 

```
最高位为符号位，1为负数，0为正数.
正数的补码是其自身.
负数的补码是将除符号位以外的所有二进制数字反转，再在末位+1.
```

 

**第二章：IF语句、逻辑运算符、循环语句以及面向对象编程**

 

1、C++中的“块”

 

```
#include <iostream>

int main(){
	//将块中多的语句看成一条语句
	{
		int x, a = 2, b = 3;
		x = a + b;
	}
}
```

 

2、类的声明

 

 

```
#include <iostream>

using namespace std;

class Human{
	//声明公有成员
	public:
		//在函数体内声明并定义
		void get_height(){ cout<<height; }
		void set_height(int x){ height = x; }
		//只在函数体内声明，在类体内只声明的成员函数只能在类外定义
		void get_weight();
		void set_weight(int );
	//声明私有成员
	private:
		int height;
		int weight;
};

//在类体外部定义Human类的公有成员函数get_weight
void Human::get_weight(){
	cout<<weight;
}

//在类体外部定义Human类的公有成员函数set_weight
void Human::set_weight(int y){
	weight = y;
}

void main(){
	Human mike;		//定义一个Human对象Mike
	mike.set_height(8);
	mike.get_weight();

	mike.set_weight(16);
	mike.get_weight();
}
```

 

3、内联函数

 

 

```
inline void func(){
	cout<<"内联函数";
}
```

 

4、