C++特殊函数方法

特殊函数方法函数

  • 静态方法(static)
  • const方法

 静态方法:this

  • 静态方法不属于特定对象,所以没有this指针。
  • 当用对象调用静态方法时,静态方法不会访问该对象的非静态数据成员。
  • 静态方法能够访问private和protected静态数据成员,并且一个对象能够经过调用静态方法访问另外一个同类型对象的private和protected静态数据成员。

const方法:编码

  • 非const对象和const对象都可以调用const方法,但const对象仅能调用const方法。
  • 实际编码时,不修改对象的全部方法声明为const,以便在程序中引用const对象。

静态方法与const方法关系:指针

  • const和static不可能同时修饰同一个函数方法,由于静态方法没有类的实例,因此不可能改变内部的值,因此二者相结合实际是多余的。

固然,若是类的成员函数不会改变对象的状态,那么该成员函数会被声明为const,但有时候须要在const函数中修改一些与类的状态无关的数据成员,那么该数据成员就应该被mutable修饰,如计算运算次数,运行效率等等。code

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();
}
相关文章
相关标签/搜索