【发布时间】:2018-03-19 12:41:30
【问题描述】:
我正在使用的示例类:
class Vector
{
double val[3];
public:
double & operator [] (const unsigned int & index) {return this->val[index];};
}
那我这样称呼它:
Vector Example;
Example[0]=5;
像这样使用运算符重载是正确的还是它反对封装,我应该使用不同的东西?我在这里使用对私有值的引用,我不确定这个实现。
【问题讨论】:
-
std::vector的索引基本上是这样工作的。 -
Setter 和 getter 恕我直言。这看起来很好并且具有预期的行为。我唯一的建议是将其写为
double& operator[](std::size_t index) {return val[index];}。另请注意,您不需要在内联函数末尾的;。 -
一旦您返回一个非常量引用,您也可以将成员设为公开,但这取决于您实际想要实现的目标
-
您当前的代码有错误吗?
-
感谢您的回答。没有错误,我只是想有良好的编程习惯,所以才问。
标签: c++ class oop operator-overloading encapsulation