当前位置: 代码迷 >> 综合 >> 34.Const(使用初始化参数列表,初始化参数)
  详细解决方案

34.Const(使用初始化参数列表,初始化参数)

热度:37   发布时间:2023-11-16 23:28:09.0

Const在基常量中使用

#include <iostream>
#include<string>int main()
{const int MAX_VALUE = 99;//第一种用法: 在*以前,能修改指针值,不能修改指针指向的值const int* a = new int;//相当于:int const* a = new int;//这样就能限制修改 a pointer指向的值//*a = 2;//但是可以修改指针地址 a指向的内存a = (int*)&MAX_VALUE;std::cout << (*a) << std::endl;//第二种用法:在*以后,能修改指针指向的值int* const b = new int;//这样就能修改 b pointer指向的值*b = 2;//但是不可以修改指针地址 b 指向的内存//b = (int*)&MAX_VALUE;std::cout << (*b) << std::endl;std::cin.get();
}

输出结果为:

99
2

Const在类中的用法

#include <iostream>
#include<string>class Entity
{
private:int m_x, m_y=99;const int const_var = 199;mutable int var; //测试 const 与 mutable 的联动public://对Entity中的参数进行初始化,分别是 m_x , m_y , const_var;//初始化 const 成员变量的唯一方法就是使用参数初始化表。Entity(int shuzi, int shuzi2, int shuzi3);void SetX(int x){m_x = x;}int GetX() const //这个成员函数将失去访问修改数据的能力{//m_y = 100;  无法执行给m_y赋值。var = 1000; //但是可以给 mutable 关键字的变量赋值return m_x;}int GetY() const{return m_y;}int Get_const_var() const{return const_var;}
};//使用初始化参数列表,初始化参数
//初始化 const 成员变量的唯一方法就是使用参数初始化表。
//注意,参数初始化顺序与初始化表列出的变量的顺序无关,它只与成员变量在类中声明的顺序有关。
Entity::Entity(int shuzi, int shuzi2,int shuzi3) :m_x(shuzi) ,m_y(shuzi2), const_var(shuzi3){}//这时候这个打印的函数,操作的就是这个实体的对象,指针指向的内容
//如果 类定义 GetX() 后面没有加 const 那么,将会报错:
// 
//错误	C2662	“int Entity::GetX(void)”: 不能将“this”指针从“const Entity”转换为“Entity& ”//&符号意味着获取对象的实体,只有也加上const关键字修饰,才能调用被const限制的相关变量return的method
void PrintEntity(const Entity& e)
{std::cout << "In class Entity , x:" <<e.GetX() << std::endl;std::cout << "In class Entity , y:" << e.GetY() << std::endl;std::cout << "In class Entity , const_var:" << e.Get_const_var() << std::endl;
}int main()
{//初始化参数表中的前三个变量Entity e(1,2,3);//修改m_x变量的值为99e.SetX(99);//调用自定义的print函数。且打印要是const的methodPrintEntity(e);std::cin.get();
}

输出结果为:

In class Entity , x:99
In class Entity , y:2
In class Entity , const_var:3

 

 

  相关解决方案