oxshit 发表于 2008-6-16 23:20

讨论:在类中怎样屏蔽对public函数返回的指针类型的修改?

如题,如下一个类:
//teat.cpp:

class teat
{
public:
        teat(int i);
        ~teat();
        int *getContext() const;
private:
        int *context;
};

teat::teat(int i)
{
      context=new int;
      *context=i;
}      

teat::~teat()
{
      if(context!=NULL)
            delete context;
}      

int *teat::getContext() const
{
      return context;
}

teat中有个public函数,返回类的私有成员context,
现在如以下:

teat t(5);
int *p=t.getContext();
*p=10;

这样就改变了context指针指向的值,而我不想让外部的调用者这样修改这个指针指向的值,可能我希望提供一个setContext这样类似的函数才能修改context的指针值,怎样修改getContext这个函数使其可以达到这样的目的呢?


页: [1]

编程论坛