使用指针访问 class 中的 getter 函数

Accessing getter functions inside a class using pointers

我刚从 C 转到 C++,所以我想了解 类 和结构之间的区别。 我正在构建一个处理二叉搜索树的代码,我正在使用 类.

class Node
{
public:
    // C'tor D'tors
    Node();
    Node(int valinput);
    ~Node();

    // Getters
    Node * getrson() const { return rson; }
    Node * getlson() const { return lson; }
    int getval() const { return val; }

    // Setters
    void setlson(Node* input) { lson = input; }
    void setrson(Node* input) { rson = input; }
    void setval(int input) { val = input; }

private:
    int val;
    Node * lson;
    Node * rson;
};

我知道我不应该直接访问私有变量,因此我应该使用 get 函数。我正在构建递归函数,所以我使用对象指针:

Node* insertion(Node* root,int val);
int checkheight(Node* root);
Node* rotate(Node* root, direction direction);

当我想访问某个节点的右子的右子时,是否需要这样写:

if(root->getrson()->getrson() != nullptr)

此代码有效吗?有什么"more natural"的写法吗?在这种情况下,我应该只使用结构而不是 类 吗?

是的,它会起作用,这是使用 getter 函数时的 "natural" 方法。

当您改为使用结构时,该行看起来不会有太大不同:

if(root->rson->rson != 0)

为了提高调用效率,您可以将getter函数设为inline。但是,大多数编译器默认情况下会隐式执行此操作以进行优化,因此不需要它。在那种情况下,使用 getter 函数没有开销。