Const
修饰变量
修饰变量后不能对变量进行修改
const int a = 10;
a = 20; // 编译错误
修饰函数
可以让参数成为常量,防止修改参数
void func(const int a) {
// 编译错误,不能修改a的值
a = 10;
}
修饰函数返回值
并没有什么意义
修饰指针
#include <iostream>
int main() {
const int *p;
int a = 10;
const int b = 20;
p = &a;
std::cout << "*p = " << *p << std::endl;
p = &b;
std::cout << "*p = " << *p << std::endl;
*p = 30;
std::cout << "*p = " << *p << std::endl; // 错误
}
可以发现修饰指针时,指针可以指向普通变量或者只读变量,但是无法通过指针修改只读变量的值。
#include <iostream>
int main() {
int a = 10;
const int *p;
p = &a;
std::cout << "*p = " << *p << std::endl;
a = 20;
std::cout << "*p = " << *p << std::endl;
}
结果如下
*p = 10
*p = 20
可以发现const int *p仅仅是将p的地址作为无法修改的常量,但是可以修改其中的值。
const int *p;
int* const p;
这是两种不同的修饰方法,一种是修饰变量,一种是修饰指针,即第一种变量的值不能改变,但指针对应地址可以改变,第二种变量的值可以改变,但指针地址不能改变。
修饰函数
普通函数
之前一直看到const修饰函数,如下进行一些尝试
#include <iostream>
void func() const {
std::cout << "114514" << std::endl;
}
int main() {
func();
}
以上程序编译错误
test.cpp:3:13: error: non-member function cannot have 'const' qualifier
void func() const {
^~~~~~
1 error generated.
可以发现普通的函数并不能这样用const修饰,只有成员函数可以这样修饰
成员函数
#include <iostream>
class A {
public:
int func() const {
// 编译错误,不能修改成员变量的值
m_value = 10;
return m_value;
}
private:
int m_value;
} A;
int main() {
A.func();
}
可以发现这样编译错误
test.cpp:7:17: error: cannot assign to non-static data member within const member function 'func'
m_value = 10;
~~~~~~~ ^
test.cpp:5:9: note: member function 'A::func' is declared const here
int func() const {
~~~~^~~~~~~~~~~~
1 error generated.
用const修饰后的成员函数不能修改类内的其他成员,这也就是成员函数用const修饰的作用
new/delete与malloc/free
malloc/free是C中的函数,new/delete是C++中的函数malloc只分配内存,new在分配内存时同时会调用构造函数,同样的,delete会调用析构函数malloc返回的是void*,需要自己转换类型,而new则不需要转换malloc需要用类似sizeof的方法传入分配类型的大小,而new则会自动计算
浙公网安备 33010602011771号