C++ notes 1

本文探讨了C++中常量与易变变量的正确声明方式,并介绍了四种显式类型转换:static_cast、const_cast、reinterpret_cast及dynamic_cast的具体用法与注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Defining a variable or function with extern is not necessary in C, but it is sometimes necessary for const in C++.

In my practice, if I define a const variable in a file, as "const int test = 100", but I could not access the constant test in other files, even though I declare extern const int test, it donen't work all the same. What should we do is to define the constant as "extern const int test = 100 ", and declare it as "extern const int test", so it will works. I find another question when I declare as "extern int test" (without the keyword const), it works when I use Dev-C++(g++ compiler based), but takes error when I use MS Visual Studio. I don't know why, but I should remember declare the full prototype.

2. The syntax volatile means "This data may change outside the knowledge of the compiler." Somehow, the environment is changing the data (possibly through multitasking, multithreading or interrupts) and volatile tells the compiler not to make any assumptions about that data, especially during optimization.

We can also create "const volatile" objects, which can't be changed by the client programmer but instead change through some outside agency. An example is status register.

3. C++explicit cast: static_cast const_cast reinterpret_cast dynamic_cast

A static_cast is used for all conversions that are well-defined. As an example, when we converse an float to int, possibly the compiler will give  a warning which said may lose information, but if we use static_cast<int>, we will eliminate warnings. A const_cast is used for coversion from a const to a nonconst or a volatile to a nonvalatile. In this way, we should modify the const value, as"const int i; int *j=const_cast<int *>(&i);(*j)++;". Dose it work? If we output the value of j and the address of i, they should be the same; and we output *j and i, possibly they will not the same. In my opinion, it should be due to the compiler optimiation. And note that we can't do simultaneous addition cast when we use explicit cast, as " double a = 100;  int * t = const_cast<int *> (&a);" It wil take an error.  And dynamic_cast I am not clear now. A reinterpret_cast  pretends that an object is just a bit pattern that can be treated(for some dark purpose) as if it were an entirely different type of object. And it is the least safe of the casting mechanism. Reference here

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值