C++特殊函数方法

特殊函数方法

  • 静态方法(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();
}

 

转载于:https://my.oschina.net/u/2959583/blog/775581

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值