一、常(常量/const)成员函数
在函数定义式()后 + const
比如:
class Rational
{
public:
//非常成员函数
void func() { cout << "func 的 调用" << endl; };
//常成员函数
void func2()const { cout << "func2 const的 调用" << endl; };
//有参构造
Rational(double d):m_d(d){}
double getRational() { return this->m_d; }
void revisegetRational(double b){ this->m_d = b ; }
private:
double m_d;
};
二、常(常量/const)对象
创建对象前 + const / 创建对象后 + const
(这就类似于const int N=1; <==> int const N=1;)
比如:
//常对象
const Rational r1(2);
//常对象
Rational const r3(3);
//非常对象
Rational r2(22);
三、注意事项:
①常对象,只能调用常成员函数(而不能调用非常成员函数)
②非 常对象,可调用常成员函数 也可调用非常成员函数
以上两点注意事项的test codes:
void test()
{
//常对象
const Rational r1(2);
//非常对象
Rational r2(22);
//r1.func();//报错!常对象r1只能调用 常成员函数 不能调用非常成员函数
r1.func2();
r2.func();
r2.func2();
}
③常成员函数不能更新(修改)类中的all非static类型的成员属性(变量),当然,常对象也是不能修改类中的all非static类型的成员属性(变量)的!
这个小细节不要忘了:static类型的成员变量只可以在类内声明,类外初始化
该注意事项的test codes:
(若你实在是想在某个常成员函数中修改成员属性的话,可以使用关键字mutable)
④常成员函数不能调用该类中没有用const修饰的成员函数,即只能调用常成员函数
该注意事项的test codes:
⑤常成员函数可以被类中其它的(常or非 常)成员函数调用
该注意事项的test codes:
class Rational
{
public:
void func() { cout << "func 的 调用" << endl; };
//void func2()const { cout << "func2 const的 调用" << endl;func(); m_Num = 1; func3(); };
void func3()const { cout << "func3 const的 调用" << endl; };
void Usefunc3() { func3(); }
Rational(double d,int m):m_d(d), m_Num(m){}
double getRational() { return this->m_d; }
void revisegetRational(double b){ this->m_d = b ; }
public:
int m_Num;
private:
double m_d;
};
⑥const关键字由于是函数类型的一部分,因此可以作为重载函数的区分条件
(
一般重载函数有3大条件才可以重载
也即:
1:函数参数类型不同(比如void func(int a ) void func(double a ))
2:函数参数个数不同(比如void func(int a ) void func(int a,int b))
3:函数参数顺序不同(比如void func(int a,double b) void func(double a,int b))
)
现在加一条
4:const也可以用于函数重载的区分!!!
该注意事项的test codes:
class Rational
{
public:
void func() { cout << "func 的 调用" << endl; };
//void func2()const { cout << "func2 const的 调用" << endl;func(); m_Num = 1; func3(); };
void func3()const { cout << "func3 const的 调用" << endl; };
void Usefunc3() { func3(); }
Rational(double d,int m):m_d(d), m_Num(m){}
double getRational() { return this->m_d; }
void revisegetRational(double b){ this->m_d = b ; }
void func()const { cout << "重载的func()的调用" << endl; }
public:
int m_Num;
private:
double m_d;
};
void test()
{
//常对象
const Rational r1(2, 1), r3(2, 1);
r1.func();//会调用func() const
}
int main()
{
test();
system("pause");
return 0;
}
Result:
参考:
[c++] 常成员函数_Zachary Yu的博客-CSDN博客
Effective C++ 之条款03