c++ 学习笔记(一)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值