一、C++基础语法
C++是一种多范式的编程语言,支持面向过程、面向对象、泛型等多种编程范式。下面我们从基本语法和常用数据类型入手,来详细阐述C++的入门内容。
1. C++的基本语法
#include <iostream>
using namespace std;
int main()
{
// 这是一个注释,不会影响程序运行
cout <<"Hello world!"<< endl;
return 0;
}2. 常用数据类型
int a = 10; double b = 3.14; char c = 'a'; bool d = true;
3. 流程控制语句
int a = 10;
if (a > 5) {
cout <<"a is greater than 5"<< endl;
} else {
cout <<"a is less than or equal to 5"<< endl;
}
for (int i = 0; i < 10; i++) {
cout <<i< 0) {
cout <<a<<"\t";
a--;
}二、面向对象编程
面向对象是C++的最大特色,C++中支持类、对象、继承、多态等重要的面向对象概念。下面我们以一个计算器程序为例,来详细介绍面向对象的用法。
1. 类和对象
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
int minus(int a, int b) {
return a - b;
}
};
int main() {
Calculator calc;
int a = 10, b = 5;
cout <<"a + b = "<< calc.add(a, b)<< endl;
cout <<"a - b = "<< calc.minus(a, b)<< endl;
return 0;
}2. 继承和多态
class Animal {
public:
virtual void sound() = 0;
};
class Dog : public Animal {
public:
virtual void sound() {
cout <<"Wang Wang!"<< endl;
}
};
class Cat : public Animal {
public:
virtual void sound() {
cout <<"Miao Miao!"<sound();
pAnimal = new Cat();
pAnimal->sound();
return 0;
}三、C++ STL
STL(Standard Template Library)是C++的标准库,包含了常用的容器、算法和迭代器等。STL提供了封装性、泛型性和可移植性,是C++编程中不可或缺的部分。
1. 容器
#include <vector>
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout <<*it<<"\t";
}2. 算法
#include <algorithm>
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
cout <<"sum: "<< accumulate(v.begin(), v.end(), 0)<< endl;
reverse(v.begin(), v.end());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout <<*it<<"\t";
}四、高级特性
除了基本语法、面向对象和STL,C++还有一些高级特性值得我们深入学习,如Lambda表达式、多线程编程和常用的异常处理等。
1. Lambda表达式
int main() {
int a = 10;
auto f = [a](int b) -> int {
return a + b;
};
cout <<f(20)<< endl;
return 0;
}2. 多线程编程
#include <thread>
void print(int x) {
for (int i = 0; i < 10; i++) {
cout <<x<<"\t";
}
}
int main() {
thread t1(print, 1);
thread t2(print, 2);
t1.join();
t2.join();
return 0;
}3. 异常处理
int main() {
try {
int a = 10, b = 0;
if (b == 0) {
throw "divide by zero";
}
cout <<a/b<< endl;
} catch (const char* msg) {
cout <<"Exception caught: "<< msg<< endl;
}
return 0;
}参考文献:
– 参考教材:C++ Primer Plus, 6th Edition.
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/256865.html
微信扫一扫
支付宝扫一扫