C++语言学习笔记分享

橙色阳光 2021-01-15 ⋅ 17 阅读

C++是一种强大且广泛使用的编程语言,它在各个领域都得到了广泛的应用。对于初学者来说,学习C++可能会有一些困难,但只要坚持下去并不断练习,你就会逐渐掌握它。在本篇博客中,我将分享一些C++语言的学习笔记,希望能够帮助你更好地理解和学习C++。

基本语法

变量和数据类型

C++中的变量必须在使用之前先声明,并且必须指定其数据类型。常见的数据类型包括整型、浮点型、字符型等。

int age = 20;
float score = 95.5;
char grade = 'A';

控制流

C++中常用的控制流语句包括条件语句和循环语句。条件语句用于根据条件来执行不同的代码块,常见的条件语句有if语句和switch语句。循环语句用于重复执行一段代码,常见的循环语句有while循环和for循环。

if (score >= 90) {
    cout << "优秀" << endl;
} else if (score >= 80) {
    cout << "良好" << endl;
} else {
    cout << "一般" << endl;
}

for (int i = 0; i < 5; i++) {
    cout << i << endl;
}

函数

函数是C++程序的基本模块,它可以接受输入参数并返回一个值。在C++中,函数的声明和定义通常分开进行,可以在头文件中声明函数,在源文件中定义函数。

// 声明函数
int square(int num);

// 定义函数
int square(int num) {
    return num * num;
}

面向对象编程

C++是一种面向对象的编程语言,它支持封装、继承和多态等特性。面向对象编程使得代码更加模块化和易于维护。

类和对象

类是C++中的一种用户自定义数据类型,它包含了数据成员和成员函数。对象是类的实例,可以通过对象来访问类中的成员。

// 定义类
class Person {
private:
    string name;
    int age;
public:
    Person(string name, int age) {
        this->name = name;
        this->age = age;
    }
    void display() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

// 创建对象
Person p("Tom", 25);
p.display();

继承与多态

继承是面向对象编程中的一个重要概念,它允许一个类从另一个类派生出来,并继承其数据成员和成员函数。多态是指同样的函数在不同的对象上表现出不同的行为。

// 基类
class Animal {
public:
    virtual void makeSound() {
        cout << "Animal makes a sound" << endl;
    }
};

// 派生类
class Dog : public Animal {
public:
    void makeSound() {
        cout << "Dog barks" << endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() {
        cout << "Cat meows" << endl;
    }
};

// 多态调用
Animal *animal1 = new Dog();
Animal *animal2 = new Cat();
animal1->makeSound();
animal2->makeSound();

标准库

C++标准库提供了丰富的函数和类,用于完成常见的任务,如字符串处理、容器管理、文件操作等。

字符串处理

C++提供了string类以及相关的成员函数,用于对字符串进行操作。

string str = "Hello, world!";
int length = str.length();
cout << "Length: " << length << endl;

string subStr = str.substr(7, 5);
cout << "Substring: " << subStr << endl;

str.replace(0, 5, "Hi");
cout << "Replaced string: " << str << endl;

容器管理

C++标准库提供了多种容器,如向量、列表、集合、映射等,用于存储和管理数据。

vector<int> numbers;
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);

for (int i = 0; i < numbers.size(); i++) {
    cout << numbers[i] << endl;
}

map<string, int> scores;
scores["Tom"] = 80;
scores["Jerry"] = 90;

cout << "Tom's score: " << scores["Tom"] << endl;

文件操作

C++提供了fstream类以及相关的成员函数,用于读写文件。

ofstream outputFile("output.txt");
outputFile << "Hello, file!" << endl;
outputFile.close();

ifstream inputFile("input.txt");
string line;
while (getline(inputFile, line)) {
    cout << line << endl;
}
inputFile.close();

总结

在本篇博客中,我分享了一些C++语言的学习笔记,包括基本语法、面向对象编程和标准库的使用。希望这些笔记能够帮助你更好地理解和学习C++。记住,不断练习是掌握C++的关键,祝你学习进步!


全部评论: 0

    我有话说: