现在的位置: 首页 > 综合 > 正文

返回内部成员变量的指针

2013年10月09日 ⁄ 综合 ⁄ 共 1560字 ⁄ 字号 评论关闭

1. 不好的方法:

先看代码

#include <iostream>
#include <cstring>

using namespace std;

const int CONTEXT_SZ=255;

class Test
{
public:
	Test() { }      
	~Test() { }

	char *getContext();
	int setContext(const char *str);

private:
	char sContext[CONTEXT_SZ];
};

char *Test::getContext()
{
	return sContext;
}

int Test::setContext(const char *str)
{
	if(strlen(str)>CONTEXT_SZ)
		return -1;

	strcpy(sContext,str);

	return strlen(sContext);
}


int main(int argc,char **argv)
{
	Test t;

	t.setContext("xxt");
	cout<<"use setContext():"<<t.getContext()<<endl;

	strcpy(t.getContext(),"AAAAAAAAAAA");
	cout<<"use getContext() to change:"<<t.getContext()<<endl;

	return 0;
}

不好的原因有二:

char *getContext()


1. 返回的是非常指针,其指向的内容可以被修改。

2. 这里我们只需取得Context的内容,不想修改他,故应该为常函数。

因此这样比较好:

cosnt char* getContext() const

{

实现略

}

2. 比较好的方法

#include <iostream>
#include <cstring>

using namespace std;

const int CONTEXT_SZ=255;

class Test
{
public:
	Test() { }      
	~Test() { }

	const char *getContext() const;    //加const限定符,不能改变类的成员变量,只能读取
	int setContext(const char *str);

private:
	char sContext[CONTEXT_SZ];
};

const char *Test::getContext() const
{
	return sContext;
}

int Test::setContext(const char *str)
{
	if(strlen(str)>CONTEXT_SZ)
		return -1;

	strcpy(sContext,str);

	return strlen(sContext);
}


int main(int argc,char **argv)
{
	Test t;

	t.setContext("xxt");
	cout<<"use setContext():"<<t.getContext()<<endl;
	//strcpy不再有效,不能复制串从char * 到const char *
	//strcpy(t.getContext(),"AAAAAAAAAAA");
	cout<<"use getContext() to change:"<<t.getContext()<<endl;

	return 0;
}

总结:

char *getContext();
改为  const char *getContext() const;

第一个const表示返回一个const指针,这样它函数不能作为左值,即不能赋值与它,而且它也只能被赋给一个const变量,这样它就不能更改,就只能进行赋值操作.

第二个const表示这是一个常量函数,不能修对象,一般get函数,都用const修饰,以防意外修改..
还可以把getContext()函数列入private中,作为私有成员函数,这样它就不能在外部修改了~~

抱歉!评论已关闭.