简体   繁体   English

类中的重载运算符,并返回对私有值的引用

[英]Overloading operator in class and returning reference to private value

Example class I'm using: 我正在使用的示例类:

class Vector
{
double val[3];
public:
double & operator [] (const unsigned int & index) {return this->val[index];};
}

Then I call it like: 然后我这样称呼它:

Vector Example;
Example[0]=5;

Is using operator overloading like this correct or it is against encapsulation and I should use something different? 是像这样正确使用运算符重载,还是反对封装,我应该使用其他方法吗? I'm using reference to private value here and I'm not sure about this implementation. 我在这里使用对私有值的引用,我不确定此实现。

Good so far... You also need one that can read from const objects. 到目前为止很好...您还需要一个可以从const对象读取的对象。 Also, there's no reason to pass an array index by const&. 另外,没有理由通过const&传递数组索引。 Also also, this-> is implicit. 同样, this->是隐式的。 Look at the member function signatures for std::vector<> . 查看std :: vector <>的成员函数签名。 In particular operator[] . 特别是operator [] Push request... 推送请求...

class Vector
{
    double val[3];
  public:
    double& operator [] (size_t index) {return val[index];};
    const double& operator [] (size_t index) const {return val[index];};
};

This is a leak in your abstraction. 这是抽象的泄漏。 It exposes the fact you have actual double s that can be read from or written to. 它揭示了您具有可以读取或写入的实际double的事实。

If you later wanted to change those double s into a remote immediate network connection data or stored in a database, you would be forced to add breaking changes to your interface. 如果以后您想将这些double更改为远程即时网络连接数据或存储在数据库中,则将不得不向接口添加重大更改。

That being said: 话虽如此:

It is worth it. 这是值得的。 You probably will never modify this type to do something that insane, and there are significant compile, design and runtime overheads to unlimited abstraction. 您可能永远都不会修改此类型以进行疯狂的操作,并且要进行无限的抽象需要大量的编译,设计和运行时开销。

Abstraction and encapsulation serve a purpose and have a cost. 抽象和封装既有目的又有成本。

std::vector<bool> 's operator[] is an example of what you can do when reference return types are not ok. std::vector<bool>operator[]是引用返回类型不正确时可以执行的operator[]的示例。 There it is used to return sub-byte elements. 在那里,它用于返回子字节元素。 Note that it is widely considered a design error. 请注意,它被广泛认为是设计错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM