类中的const成员函数
1.const对象的声明和初始化
类内定义:
class
A
{
int
x;
public
:
A():x(1){}
void
print1()
const
{
cout
<<
2
<<
endl;
}
};
类外定义:
class
A
{
int
x;
public
:
A():x(1){}
void
print1()
const
;
};
void
A
::print1()
const
{
cout
<<
1
<<
endl;
}
2.const的作用:
普通成员函数:return_type func(A *const this,....);
const成员函数:return_type func(const A *const this,....);
普通成员函数this指针原本有顶层const,而const成员函数this指针多了一个底层const,表示const成员函数不能修改对象的成员数据,但是可以修改类的静态成员数据。
class
A
{
public
:
int
x;
static
int
y;
A(
int
x
=1):x(
x
){}
void
print()
const
{
y++;
cout
<<
y
<<
endl;
}
};
int
A
::y = 2;
int
main() {
A
a;
a.print();
return
0;
}
输出:3
当数据成员为指针时,可以修改指针指向的对象:
class
A
{
public
:
int
x;
int
* ptr;
A(
int
x
= 1) :x(
x
) { ptr =
new
int
(1); }
void
print()
const
{
*ptr = 2;
cout
<<
*ptr
<<
endl;
}
~A() {
delete
ptr;
}
};
int
main() {
A
a;
a.print();
return
0;
}
输出:2
3. 常量对象
常量对象只能访问const成员函数,普通对象可以访问普通成员函数和const成员函数。
成员函数通过const重载:
调用顺序:常量对象只能调用const成员函数
普通对象当函数优先调用普通成员对象
-
先调用参数最为匹配的成员函数(可以隐式转换)
-
再参数相同的情况下,普通成员函数优先调用普通成员函数。
class
A
{
int
x;
public
:
A():x(1){}
void
print1(
double
x
)
const
{
cout
<<
x
<<
endl;
}
void
print1() {
cout
<<
2
<<
endl;
}
};
int
main() {
A
a;
a.print1(3);
return
0;
}
输出:3
![](https://i-blog.csdnimg.cn/blog_migrate/8f8f42c6b21e02d3e5c52adcc0386af6.png)
class
A
{
int
x;
public
:
A():x(1){}
void
print1() {
cout
<<
x
<<
endl;
}
void
print1()
const
{
cout
<<
x+1
<<
endl;
}
};
int
main() {
A
a;
a.print1();
return
0;
}
输出:1