const类型对象只能调用const类型函数
来源:互联网 发布:皇太子的王子网络剧01 编辑:程序博客网 时间:2024/05/21 07:46
例子:
class A {
public:
A():num(2) { }
~A() { }
void setnum() const { num = 10; }
void getnum() const{ printf("%d\\n",num); }
private:
int num;
};
int main()
{ A b;
b.setnum();
return 0; }
可以注意到,编译以上这段代码会出现编译错误(l-value specifies const object)!,避免错误的方式为:
方法1.重新定义变量num为:mutable int num;(在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中。)
方法2.修改setnum函数为void setnum() const { }
因为setnum函数被声明为const了,这样一来,在编译器的编译过程中,就将这个类方法中的影藏参数this转换成了const this,这样一来,自然就不能对类成员进行修改了。 现在在来看下返回值为const的函数有什么作用:
class A
{
public:
A():num(2)
{
}
~A()
{
}
void setnum()
{
num = 10;
}
void getnum() const{
printf("%d\\n",num);
}
private:
int num;
};
class B
{
public:
B()
{
}
~B()
{
}
const A* get()
{
A *p = new A();
return p;
}
};
int main()
{
B b;
b.get()->getnum();
b.get()->setnum();
return 0;
}
{
public:
A():num(2)
{
}
~A()
{
}
void setnum()
{
num = 10;
}
void getnum() const{
printf("%d\\n",num);
}
private:
int num;
};
class B
{
public:
B()
{
}
~B()
{
}
const A* get()
{
A *p = new A();
return p;
}
};
int main()
{
B b;
b.get()->getnum();
b.get()->setnum();
return 0;
}
现在我们通过类B的方法get()来获得一个类A的实体const对象
,你会发现程序也编不过,原因其实类似,const类型的对象,不能调用自身的非const成员函数,但是可以调用自己的const成员函数。
0 0
- const类型对象只能调用const类型函数
- const 对象只能调用 const 函数
- const 对象只能调用const函数
- 项目中的错误:const对象只能调用const函数
- C++细节学习之const对象只能调用const函数
- 为什么const对象只能调用const成员函数,而不能调用非const成员函数?
- 为什么const对象只能调用const成员函数,而不能调用非const成员函数?
- C++回顾之const对象、const成员函数、mutable类型
- 函数返回的临时对象为const类型,const引用
- C++回顾之const对象、const成员函数、mutable类型
- const类型参数的对象引用和const成员函数
- C++之const对象只能调用const成员函数---补充(18)《More Effective C++》
- Const 类型
- const 类型
- const对象调用非const成员函数
- [C++] const对象只能调用const方法的原因
- const 作为函数返回类型
- const类型的成员函数
- 硬盘容量如何计算? 硬盘容量说明
- Git 常用的 8 个命令初步
- android关于控件中setTag(key,Object)的设置的相关问题
- linux(suse)系统时间的同步和修改
- 工作记录--linux_c学习资料
- const类型对象只能调用const类型函数
- 综合思路养成记之会计怎么学
- Java基础回顾_IO流_File简单操作
- 68_leetcode_Symmetric Tree
- 中断处理程序不能使用printf的本质
- PCI/PCI Express体系结构
- perl函数说明(delete)
- HDU 3177 Crixalis's Equipment 贪心
- 如何编写更棒的代码:11个核心要点