c++ 学习笔记(一)

  数据类型

  • typedef 声明

为一个已经存在的类型重新定义一个名称

#include <iostream>
using namespace std;

int main(){
    typedef int hello;
    hello a = 10;
    cout << a;
    return 0;
}

将int类型冲洗定义一个名称 hello,只是起了一个新的名字原来的还是可以继续使用的

  • 枚举类型
#include <iostream>
using namespace std;

int main(){
    enum color {red,green=10,blue} c;
    c = blue;
    cout << c;
    return 0;
}

如何为变量c赋的值不是enum中的值时则会报错

 

  声明变量

  • extern 关键字

extern可以置于变量或者函数前,以标示变量或者函数的定义在别的文件中,提示编译器遇到此变量和函数时在其他模块中寻找其定义

main.cpp

#include <iostream>
using namespace std;
extern int a;

int main(){
    cout << a;
    return 0;
}

  test.cpp

#include <iostream>
using namespace std;

int a = 20;

结果输出 20

  定义常量

  定义常量可以使用两种方式   #define   const  两者的区别在于:

  1.类型检查不同,#define 不会检查常量的类型而只是单纯的将常量替换为预先定义的值;const 定义常量时需要指定常量的类型

  2.#deifne 定义的常量可以使用 #undef 来取消,但是const定义的常量不能更改

  3.定义域不同 #define 定义好的常量不受定义域限制 const 定义的常量有定义域的限制

#include <iostream>
using namespace std;

void declam(){
    #define COUNT 20
    const int SUM = 10;
}

int main(){
    cout << COUNT;
    cout << SUM <<endl; //error: 'SUM' was not declared in this scope
    return 0;
}
原文地址:https://www.cnblogs.com/itsuibi/p/11226031.html