简体   繁体   English

无法保持我的健康

[英]Can't get my constness right

I have a Node class defined like this (this is a minimal version): 我有一个像这样定义的Node类(这是一个最低版本):

class Node {
    private:
        std::vector <const Node*> leaves;

     public:
        Node* getLeaf(int i);
}

In other words, I want getLeaf to return a pointer to an element of the vector "leaves" 换句话说,我希望getLeaf返回指向向量“ leaves”的元素的指针

I tried defining getLeaf like so 我试图像这样定义getLeaf

Node* Node::getLeaf(int i){
    return leaves[i];
}

Ok, so I know I'm screwing the constness up. 好的,所以我知道我正在搞砸常量性。 I've tried variations of const modifiers in my function declarations / definitions to no luck. 我在函数声明/定义中尝试了const修饰符的变体,但没有走运。 Someone please help :) 有人请帮忙:)

const is a promise to not change. const承诺不会改变。

You declare a vector of pointers to const nodes. 您声明一个指向const节点的指针向量。 That's a promise to not change any Node via these pointers. 保证不会通过这些指针更改任何Node

The getLeaf function can't very well then return a pointer to non- const node, because then the caller can do anything with the node. 然后, getLeaf函数不能很好地返回一个指向非const节点的指针,因为调用者可以对该节点执行任何操作。

So you have to make either the same promise both places, or don't make any such promise. 因此,您必须在两个地方都做出相同的承诺,或者不要做出任何这样的承诺。


Another matter is whether getLeaf itself should be const (it probably should, it makes sense to let it promise not to change the object), and a second other matter is whether get makes sense as a prefix in C++ (usually not, it's just needless verbosity, while in Java there are tools that can make good use of such of prefix), I'd just call it node . 另一件事是getLeaf本身是否应为const (可能应该,让它保证不更改对象是有意义的),第二件事是get意义是否应作为C ++中的前缀(通常不是,这是不必要的)冗长,而在Java中,有一些工具可以很好地利用诸如此类的前缀),我只称其为node

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

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