2025.8.10-学习C++(一)

检查 GCC 版本

复制代码
g++ --version
cpp 复制代码
#include <iostream>
/*
This is a multi-line comment
You can write multiple lines of explanation
Without worrying about adding // to each line
*/
int main() {
// Print a greeting message
    std::cout << "Hello,World!" << std::endl;
    return 0;
}

#include <iostream>:这是一个包含输入/输出流库的预处理器指令。它允许我们使用输入和输出操作,例如打印到屏幕。

  • 每个 C++ 程序都必须有一个main()函数
  • 函数main()是程序执行的开始
  • return 0;语句通常用于指示程序执行成

cout是 C++ 标准输入/输出库的一部分,用于显示输出。

  • std::cout:这是标准输出流对象
    • std::表示我们正在使用标准命名空间
    • cout代表"控制台输出"
  • <<:流插入操作符,用于将数据发送到输出流
  • std::endl:添加新行并刷新输出缓冲区
    • 确保消息立即显示
    • 将光标移动到下一行

编译 .cpp 文件

cpp 复制代码
g++ hello.cpp -o hello
  • -o hello:指定输出可执行文件名称
    • -o是一个允许您命名输出文件的选项
    • hello是创建的可执行文件的名称

使用 ./hello 命令执行程序

单行注释 ://; 多行注释: 开始/*,结尾*/

使用 endl 和 \n 进行换行

cpp 复制代码
#include <iostream>

int main() {
    std::cout << "Mixing methods: " << std::endl;
    std::cout << "Line with endl\n";
    std::cout << "Line with newline character" << std::endl;

    return 0; // Return success status to the operating system
}
cpp 复制代码
#include <iomanip>
std::cout << std::fixed << std::setprecision(4);
//格式化浮点数输出
//std::fixed-用来指定浮点数 以固定小数点格式输出
//std::setprecision(4)-用来指定 小数点后的精度(位数)

使用 #include <string> 访问字符串功能

cpp 复制代码
#include <iostream>
#include <string>

int main() {
    // Declaring and initializing string variables
    std::string greeting = "Hello, World!";
    std::string name = "John Doe";
    std::string empty_string;

    // Printing string variables
    std::cout << "Greeting: " << greeting << std::endl;
    std::cout << "Name: " << name << std::endl;

    // String concatenation
    std::string welcome = greeting + " Welcome, " + name;
    std::cout << "Welcome Message: " << welcome << std::endl;

    // String length
    std::cout << "Greeting length: " << greeting.length() << std::endl;

    // Accessing individual characters
    std::cout << "First character of name: " << name[0] << std::endl;

    // Modifying strings
    name = "Jane Smith";
    std::cout << "Updated Name: " << name << std::endl;

    return 0;
}

类型转换

cpp 复制代码
static_cast<int>
cpp 复制代码
// Defining constants with const keyword
    const int MAX_USERS = 100;
    const double PI = 3.14159;
    const char GRADE_SEPARATOR = '-';
//对常量名称使用大写

std::boolalpha

cpp 复制代码
std::cout << "Is Student: " << std::boolalpha << isStudent << std::endl;
// std::boolalpha打印"true"/"false"而不是 1/0

sizeof() 检查不同数据类型的内存大小

cpp 复制代码
#include <iostream>

int main() {
    // Checking memory size of integer types
    std::cout << "Integer Types Memory Size:" << std::endl;
   

    // Checking memory size of character and boolean types
    std::cout << "\nOther Types Memory Size:" << std::endl;
    std::cout << "char: " << sizeof(char) << " bytes" << std::endl;
    std::cout << "bool: " << sizeof(bool) << " bytes" << std::endl;

    // Checking memory size of specific variables
    int intVar = 42;
    double doubleVar = 3.14;
    char charVar = 'A';

    std::cout << "\nVariable Memory Size:" << std::endl;
    std::cout << "intVar: " << sizeof(intVar) << " bytes" << std::endl;
    std::cout << "doubleVar: " << sizeof(doubleVar) << " bytes" << std::endl;
    std::cout << "charVar: " << sizeof(charVar) << " bytes" << std::endl;

    return 0;
}

//short: 2 bytes
//int: 4 bytes
//long: 8 bytes
//long long: 8 bytes

//Floating-Point Types Memory Size:
//float: 4 bytes
//double: 8 bytes
//long double: 16 bytes

//Other Types Memory Size:
//char: 1 bytes
//bool: 1 bytes

整数溢出:当值超过类型的最大限制时发生

cpp 复制代码
#include <iostream>
#include <limits>

int main() {
    // Demonstrating integer overflow with short int
    short smallInt = 32767;  // Maximum value for short
    std::cout << "Original Value: " << smallInt << std::endl;

    // Overflow occurs when incrementing beyond maximum
    smallInt++;
    std::cout << "After Overflow: " << smallInt << std::endl;

    // Using unsigned integers to prevent negative overflow
    unsigned int positiveOnly = 0;
    std::cout << "Unsigned Integer Start: " << positiveOnly << std::endl;

    // Decrementing unsigned integer causes wrap-around
    positiveOnly--;
    std::cout << "Unsigned Integer Wrap-around: " << positiveOnly << std::endl;

    // Checking integer limits
    std::cout << "\nInteger Type Limits:" << std::endl;
    std::cout << "Short Max: " << std::numeric_limits<short>::max() << std::endl;
    std::cout << "Short Min: " << std::numeric_limits<short>::min() << std::endl;

    // Safe increment method
    try {
        if (smallInt < std::numeric_limits<short>::max()) {
            smallInt++;
            std::cout << "Safe Increment: " << smallInt << std::endl;
        } else {
            std::cout << "Cannot increment further" << std::endl;
        }
    } catch (const std::overflow_error& e) {
        std::cout << "Overflow Error: " << e.what() << std::endl;
    }

    return 0;
}
/*
Original Value: 32767
After Overflow: -32768
Unsigned Integer Start: 0
Unsigned Integer Wrap-around: 4294967295

Integer Type Limits:
Short Max: 32767
Short Min: -32768
Safe Increment: -32767
*/

在 C++ 中,整数除法 (9/5) 的结果是 1,而不是 1.8;使用浮点值 (9.0/5.0) 以获得准确的结果

cpp 复制代码
#include <iostream>

int main() {
    // Basic ternary operator syntax
    // condition ? value_if_true : value_if_false

    // Simple comparison
    int x = 10;
    int y = 5;

    // Determine the larger number
    int max_value = (x > y) ? x : y;
    std::cout << "Larger value: " << max_value << std::endl;

// 10
// condition ? value_if_true : value_if_false;if else语法

函数

cpp 复制代码
return_type function_name(parameters) {
    // Function body
    return value;
}
// return_type:函数返回值的数据类型。如果函数不返回任何值,则使用关键字 void。
cpp 复制代码
void swapValues(int& a, int& b) {
    // Directly modify the original variables
    int temp = a;
    a = b;
    b = temp;
}
// int& a 和 int& b 是引用(reference),它们并不是实参的拷贝,而是直接指向调用函数时传入的变量。
// 因此,在函数内部对 a、b 的修改会直接作用在实参上。
cpp 复制代码
unsigned long long calculateFactorialWithSteps(int n, int depth = 0)
// unsigned long long,足够大,可以存放较大阶乘结果。

头文件.h

cpp 复制代码
#ifndef HEADER_NAME   // 如果没有定义 HEADER_NAME
#define HEADER_NAME   // 定义 HEADER_NAME

// 头文件的内容

#endif  // 结束条件编译
  • ifndef

    • "if not defined"的缩写。

    • 检查某个宏是否没有定义

    • 如果没有定义,就编译接下来的代码。

  • #define

    • 定义一个宏。

    • 在这里,它的作用不是用来替换文本,而是作为一个 标记,告诉编译器"这个头文件已经被包含过一次"。

  • #endif

    • 表示条件编译的结束。

    • 对应 #ifndef 的结束大括号。

cpp 复制代码
stats.average = static_cast<double>(stats.sum) / size;
// 类型转换运算符,用来在编译时进行 显式类型转换。

结构体:

cpp 复制代码
#include <iostream>
using namespace std;

struct MathStats {
    int sum;
    double average;
    int minimum;
    int maximum;
};

int main() {
    MathStats stats; // 定义一个结构体变量

    stats.sum = 50;
    stats.average = 12.5;
    stats.minimum = 3;
    stats.maximum = 20;

    cout << "Sum: " << stats.sum << endl;
    cout << "Average: " << stats.average << endl;
    cout << "Min: " << stats.minimum << endl;
    cout << "Max: " << stats.maximum << endl;

    return 0;
}
相关推荐
爱吃生蚝的于勒1 天前
【Linux】深入理解进程(一)
java·linux·运维·服务器·数据结构·c++·蓝桥杯
自由会客室1 天前
在 Ubuntu24.04 上安装 JDK 21(Java 21)
java·开发语言
chuyanghong1 天前
Ubuntu下VIM安装及配置
c++
喜欢读源码的小白1 天前
SpringBoot的启动流程原理——小白的魔法引擎探秘
java·开发语言·spring boot·springboot启动原理
Han.miracle1 天前
数据结构——排序的学习(一)
java·数据结构·学习·算法·排序算法
boss-dog1 天前
崩溃信息追溯——backward-cpp
c++·debug·backward-cpp
夜幽青玄1 天前
mybatis-plus调用报 org.springframework.dao.DataIntegrityViolationException 错误处理
开发语言·python·mybatis
洲覆1 天前
Redis 内存淘汰策略
开发语言·数据库·redis·缓存
电子云与长程纠缠1 天前
Blender入门学习01
学习·blender
偶尔贪玩的骑士1 天前
Kioptrix Level 1渗透测试
linux·开发语言·网络安全·php