我正在通过编写一个名为 Node
的类来实现一棵树,我遇到了有关以下方法和成员变量的问题:
class Node {
public:
// ...
void addChild(const std::shared_ptr<Node> node);
private:
// ...
std::vector< std::shared_ptr<Node> > _children;
std::shared_ptr<Node> _parent;
};
当 addChild
被 Node
调用对象,它只是应该设置参数的 _parent
成员指向调用者,然后将参数添加到调用者的 child vector 中。我的实现目前看起来像这样:
void Node::addChild(const std::shared_ptr<Node> node) {
if (!node) {
std::invalid_argument("Argument node must be nonnull.");
}
*node._parent = this;
_children.push_back(node);
}
麻烦的线路是*node._parent = this;
,这会导致此错误:
src/Node.cpp:89:10: error: no member named '_parent' in
'std::__1::shared_ptr<Node>'; did you mean to use '->' instead of '.'?
我的思路告诉我我正在取消引用 node
访问实际的 Node
对象,然后使用 ._parent
访问 _parent
成员。自 _parent
是 std::shared_ptr<Node>
, 然后将其设置为等于 this
才有意义, 这是一个指向调用对象的指针。但是为什么我的编译器告诉我 _parent
当它确实存在时不存在?
编辑:我也已经尝试过 (*node)._parent
, node->_parent
, (*node)->_parent
, 和 *(*node)._parent
,都无济于事。它们都导致 error: no viable overloaded '='
.
最佳答案
您的代码行:*node._parent = this;
有两个问题:
- 运算符优先级
- 分配给
shared_ptr
第一运算符优先级。运算符 .
在运算符 *
之前计算。所以目前你的代码类似于这样做:
*(node._parent)
node
没有 _parent
成员,但是 *node
有。因此,通过以下任一方法修复它:
(*node)._parent
或者更好:
node->_parent
然后,你有另一个问题,你不能像这样用 operator =()
分配给 shared_ptr
。你需要改变
= this;
收件人:
.reset(this);
总的来说,
node->_parent.reset(this);
关于c++ - 在以下情况下,如何正确取消引用对象以设置它的成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32484026/