C++常成员函数 - const 关键字
来源:互联网 发布:淘宝店如何提高销量 编辑:程序博客网 时间:2024/06/08 19:06
常成员函数详解
声明:<类型标志符>函数名(参数表)const;
说明:
(1)const是函数类型的一部分,在实现部分也要带该关键字。
(2)const关键字可以用于对重载函数的区分。
(3)常成员函数不能更新类的成员变量,也不能调用该类中没有用const修饰的成员函数,只能调用常成员函数。
(4)常对象只能调用常成员函数。 普通对象可以调用全部成员函数。
A、通过例子来理解const是函数类型的一部分,在实现部分也要带该关键字。
class A{
private:
int w,h;
public:
int getValue() const;
int getValue();
A(int x,int y)
{
w=x,h=y;
}
A(){}
};
int A::getValue() const //实现部分也带该关键字
{
return w*h; //????
}
void main()
{
A const a(3,4);
A c(2,6);
cout<<a.getValue()<<c.getValue()<<"cctwlTest";
system("pause");
}
B、通过例子来理解const关键字的重载
class A{
private:
int w,h;
public:
int getValue() const
{
return w*h;
}
int getValue(){
return w+h;
}
A(int x,int y)
{
w=x,h=y;
}
A(){}
};
void main()
{
A const a(3,4);
A c(2,6);
cout<<a.getValue()<<c.getValue()<<"cctwlTest"; //输出12和8
system("pause");
}
C、通过例子来理解常成员函数不能更新任何数据成员
class A{
private:
int w,h;
public:
int getValue() const;
int getValue();
A(int x,int y)
{
w=x,h=y;
}
A(){}
};
int A::getValue() const
{
w=10,h=10;//错误,因为常成员函数不能更新任何数据成员
return w*h;
}
int A::getValue()
{
w=10,h=10;//可以更新数据成员
return w+h;
}
void main()
{
A const a(3,4);
A c(2,6);
cout<<a.getValue()<<endl<<c.getValue()<<"cctwlTest";
system("pause");
}
D、通过例子来理解
1、常成员函数可以被其他成员函数调用。
2、但是不能调用其他非常成员函数。
3、可以调用其他常成员函数。
class A{
private:
int w,h;
public:
int getValue() const
{
return w*h + getValue2();//错误的不能调用其他非常成员函数。
}
int getValue2()
{
return w+h+getValue();//正确可以调用常成员函数
}
A(int x,int y)
{
w=x,h=y;
}
A(){}
};
void main()
{
A const a(3,4);
A c(2,6);
cout<<a.getValue()<<endl<<c.getValue2()<<"cctwlTest";
system("pause");
}
- C++常成员函数 - const 关键字
- C++常成员函数 - const 关键字
- C++常成员函数 - const 关键字
- C++常成员函数 - const 关键字
- const用法之常对象,常成员函数,常引用
- 含有const关键字成员函数
- const关键字类成员函数
- const 修饰的常函数成员
- void f() const 常成员函数
- c++const成员函数
- 常成员函数:Const类限定的成员函数
- C++常数据成员精讲—const关键字
- C++常数据成员精讲—const关键字
- C++常数据成员精讲—const关键字
- 常成员const
- const成员函数和mutable关键字
- C++ Const关键字修饰变量、成员函数!
- C++ Const关键字修饰变量、成员函数!
- 笔记(二叉树堆栈实现)
- 华为2015校园招聘机试题
- Jquery选择器
- HDU-#1026 Ignatius and the Princess I(BFS+优先队列+路径存储)
- 排名前十的SQL和NoSQL数据库
- C++常成员函数 - const 关键字
- js提示信息的写法
- eclipse SVN中文件修改后图标不变黑星解决
- Visual Studio easyUI中json数据无法加载办法
- 学习笔记:如何成为一个优秀的scrum master
- linux 补丁文件, 一个最简单的patch的格式
- C# 事件和Unity3D
- vb(不是vb.net)字符串多行书写
- 主题:QUI框架V3.3版本正式发布!