C++:在不破坏封装的情况下使用指针作为私有成员变量



我有一个类Film,它包含一个整数指针Chapitres和该数组Count_Chapitres的元素数。

class film : public video
{
private:
int* Chapitres;
unsigned int Count_chapitres;
public:
film();
film(int* Chapitres, unsigned int Count_Chapitres, int Duree, string Name, string Filename);
virtual ~film();
void setChapitres (int * Chapitres, unsigned int Count_Chapitres);
int * getChapitres() const;
unsigned int getCountChapitres() const;
void printOut (ostream & Display) const;
};

显而易见的问题是,泄露指针会破坏封装

1( 我曾尝试将get的输出设置为const int*,在这种情况下,只需使用const_cast将输出强制转换回度量值即可。由于以下允许邪恶指针从外部更改胶片数据:

film* file2 = new film(Chaps, 3, 5, "hany", "daher");
file2->printOut(cout);
int * Evil = const_cast<int *>(file2->getChapitres());
*(Evil +1)=9;
file2->printOut(cout);

2( 此外,即使我将const int*作为构造函数/setter的参数,它仍然将int*对象作为main的参数,这使得const关键字本质上是多余的。

解决方案显然不在于指向常数值的指针。你知道如何继续吗?

您需要理解封装是"枪支安全开关"中的保护,而不是"强加密"中的。您不应该再担心类用户使用返回的const pointer执行const_cast的可能性,就像您担心他们在包含头类之前键入类似#define private public的内容一样。

在C++中,故意破坏封装的可能性是无限的,无论是有外部行为还是没有外部行为。相反,封装试图保护类的用户免受无辜错误的影响。

在您的特定情况下,您需要常量限定getter函数并返回const int*。或者,由于您已经有了琐碎的getter和setter,您可以取消它们,只需使用相同级别的封装将您的成员声明为公共即可。

最新更新