«

1 C++基础入门

时间:2023-9-16 23:20     作者:wen     分类: C++


[toc]

一、C++初识

第一个C++程序

编写一个c++程序总共分为4个步骤

创建项目

用Visual Studio创建C++空项目

创建文件

在源文件夹创建一个helloworld.cpp

编写代码

# helloworld.cpp

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello World" << endl;
    system("pause");
}

注释

注释:在代码中一些说明和解释,方便自己或其他程序员阅读代码。

两种格式

  1. 单行注释: //描述信息
    1. 通常放在一行代码的上方。或者一条语句的末尾。对该行代码说明
  2. 多行注释:/*描述信息*/
    1. 通常放在一段代码的上方。对该代码做整体说明。

提示:编辑器在编译代码时,会忽略注释的内容。

#include <iostream>

using namespace std;

// 多行注释
/*
main是一个程序的入口
每个程序都必须有这么一个函数
有且仅有一个
*/
int main()
{
    // 1. 单行注释
    // 在屏幕中输出一个hello world
    cout << "Hello World" << endl;
    system("pause");
}

变量

作用:给一段指定的内存空间起名,方便操作这段内存。

语法:数据类型 变量名 = 初始值;

示例:

#include <iostream>

using namespace std;

int main()
{
    // 变量创建的语法: 数据类型 变量名 = 初始值;
    int a = 10;

    cout << "a=" << a << endl;

    system("pause");
}

常亮

作用:用于记录程序中不可更改的数据。

C++定义常量两种方式

  1. #define 宏常量:#define 常量名 常量值
    1. 通常在文件上方定义,表示一个常量。
  2. const修饰的变量const 数据类型 常量名 = 常量值
    1. 通常在变量定义前加关键字const,修饰该变量为常量,不可修改。好的那我们一周八年你这个是事儿吗肯定是不认的对不对那一年有多少个月份呢啊

示例:

#include <iostream>

using namespace std;
// 宏常量定义方式
#define Day 7

int main()
{

    cout << "一周总共有" << Day << "天" << endl;
    // const修饰的变量
    const int month = 12;

    cout << "一年有" << month << "月" << endl;
    system("pause");
}

关键字

作用:关键字是c++中预先保留的单词(标识符)。

标识符大标时候,他说的也是一个意思。

在定义变量或者常量时候,不要用关键字


auto break case catch char
class const constexpr continue default
delete do double else enum
explicit export extern false float
for friend goto if inline
int long mutable namespace new
noexcept nullptr operator private protected
public register reinterpret_cast return short
signed sizeof static static_assert static_cast
struct switch template this throw
true try typedef typeid typename
union unsigned using virtual void
volatile wchar_t while alignas alignof
char16_t char32_t decltype thread_local char8_t
concept requires co_await co_return co_yield

提示:再给变量或常量起名称时候不要用c++的关键字,否则会产生歧义。

标识符命名规则

作用:C++规定给标识符(变量、常量)命名时。有一套自己的规则。

建议:给标识符命名时,争取做到见名知意的效果,方便自己和他人的阅读。

标签: C/C++