沈阳网站建设,免费销售网站模板,做电商网站需要会些什么条件,社区网站开发详解const《老九学堂C课程》《C primer》学习笔记。《老九学堂C课程》详情请到B站搜索《老九零基础学编程C入门》-------------简单的事情重复做#xff0c;重复的事情用心做#xff0c;用心的事情坚持做(老九君)---------------1.const修饰成员变量 2.const修饰函数参数 3.c…
详解const 《老九学堂C课程》《C primer》学习笔记。《老九学堂C课程》详情请到B站搜索《老九零基础学编程C入门》 -------------简单的事情重复做重复的事情用心做用心的事情坚持做(老九君)---------------1.const修饰成员变量 2.const修饰函数参数 3.const修饰返回值 4.const 修饰函数
//
// Created by 陈莹莹 on 2021/2/25.
//#ifndef CHAPTER12_CONSTDEMO_H
#define CHAPTER12_CONSTDEMO_H
#include iostream
using namespace std;
//1.const修饰成员变量
void ConstDemo1(){int num1 1024;const int num2 num1; //常量第一次赋值的时候没有错// num2 2048; //第二次赋值的时候就报错了const int *ptr1_num1 num1; // (与下面这一行等价吧)编译能够过, 不能通过指针去改num1,指针本身可以改指int const *ptr2_num1 num1; // 合法ptr1_num1 num2; // 合法内容const指针再指向没问题//*ptr1_num1 1024; // 不合法内容const指针指向的内容无法修改// const修饰指针变量时// 1.只有一个const时如果const 位于*的左侧表示指针所指的数据时常量不能通过改指针去自改实际数据指针可以改指// 2.只有一个const时如果const 位于*的右侧表示指针身上时常量不能指向其他内存单元指针所是指向的数据可以修改// 3.两个const位于*的左右两侧表示指针和指针所指向的数据都不能修改int * const ptr3_num1 num1;// ptr3_num1 ptr2_num1; // 不合法
}
// 2.const修饰函数参数
void ConstTest2(const int num){// num 123; // 不合法传递来的参数num在函数体内部不可改变与修饰变量的性质一致
}
class Computer{
public:Computer(int core){this-m_core core;}void buy(int core){}/** 修改电脑的核心频率 */void SetCore(int core){this-m_core core;}int GetCore() const {return m_core;}private:int m_core; // cpu的主频
};
void ConstTest3(const Computer computer){// const 修饰引用时不能修改引用变量的成员-// 好处可以保护传递的参数不需要一个新的参数副本// computer.buy(123); // 不合法// 使用cosnt传递对象的引用时可以起到不copy对象的目的节省效率// 需要在成员函数的圆括号后加一个const 修饰void buy(int core) const{}
}
//3.const修饰返回值。返回引用加const 效率更高
//强调使用const 修饰引用类型的一个常见原因是提高效率
const Computer GetMax(const Computer com1, const Computer com2){if(com1.GetCore() com2.GetCore()){return com1;}return com2;
}
//如果函数要返回局部对象就应该直接返回这个对象而不是返回对象的引用
const Computer GetMax1(const Computer com1, const Computer com2){Computer com3(2); // 不返回引用是一副本的形式生成if(com1.GetCore() com2.GetCore()){return com1;}else{com3 com2;}return com3;
}
// 在可以返回对象也可以返回引用时首选返回引用高因为效率高//4.const 修饰函数-- 说明函数不会修改成员变量的值
class TestClass{
public:int value;void ModifyValue(){value 1111;}
};
//为了在重载运算符时更有效
#endif //CHAPTER12_CONSTDEMO_H