首页 > 解决方案 > 通过 const 引用传递指针

问题描述

通过 const 引用传递指针不是为了优化吗?

前任。

bool testHelper(const TreeNode*& p, const TreeNode*& q) {
    return false;
}

TreeNode* test(TreeNode* root, TreeNode* p, TreeNode* q) {
    recursiveHelper(p, q);
}

错误:

Line 17: Char 28: error: binding reference of type 'const TreeNode *' to value of type 'TreeNode *' not permitted due to incompatible qualifiers
                testHelper(p, q);
                           ^
Line 12: Char 42: note: passing argument to parameter 'p' here
        bool testHelper(const TreeNode*& p, const TreeNode*& q) {
                                         ^

标签: c++pointersreferenceconstants

解决方案


通过 const 引用传递指针不是为了优化吗?

不,不是,因为它并没有更快。添加的间接性可能会更慢。

bool testHelper(const TreeNode*& p, const TreeNode*& q) 

这些不是对 const 的引用。这些是对指向 const 的非 const 指针的引用。


其他错误:

  • test被声明为非无效返回但缺少返回语句
  • 您尚未声明recursiveHelper您调用的函数。

推荐阅读