特殊函数方法
- 静态方法(static)
- const方法
静态方法:
- 静态方法不属于特定对象,因此没有this指针。
- 当用对象调用静态方法时,静态方法不会访问该对象的非静态数据成员。
- 静态方法可以访问private和protected静态数据成员,而且一个对象可以通过调用静态方法访问另一个同类型对象的private和protected静态数据成员。
const方法:
- 非const对象和const对象均可以调用const方法,但const对象仅能调用const方法。
- 实际编码时,不修改对象的所有方法声明为const,以便在程序中引用const对象。
静态方法与const方法关系:
- const和static不可能同时修饰同一个函数方法,因为静态方法没有类的实例,所以不可能改变内部的值,所以两者相结合实际是多余的。
当然,如果类的成员函数不会改变对象的状态,那么该成员函数会被声明为const,但有时候需要在const函数中修改一些与类的状态无关的数据成员,那么该数据成员就应该被mutable修饰,如计算运算次数,运行效率等等。
2.举例
class test
{
public:
static int getNumber();
string getString()const;
int setNumber(int x);
static int getAnotherNumber(test anothertest);
private:
static int n;
string s;
};
int test::n = 0;
int test::getNumber()
{
//return this->n;//this只能用于非静态成员函数内部
//string s1 = s;//静态成员函数仅能访问静态数据成员
return n;//访问private成员变量
}
int test::setNumber(int x)
{
this->n = x;
return this->n;
}
string test::getString()const
{
return s;
}
int test::getAnotherNumber(test anothertest)
{
return anothertest.n;
}
void main()
{
test onetest, twotest;
onetest.setNumber(8);
twotest.setNumber(9);
cout << onetest.getAnotherNumber(twotest)<<endl;//个对象可以通过调用静态方法访问另一个同类型对象的private和protected静态数据成员。
const test threetest;
cout<<threetest.getNumber()<<"\n";
//cout << threetest.setNumber(5);//常量对象仅能调用const方法
getchar();
}