【问题标题】:Pass Reference in Class在类中传递参考
【发布时间】:2011-08-03 20:07:31
【问题描述】:

我完全糊涂了。在这个属于我的课程的示例中,我有:

public:
        typedef DoubleLinkedNode<DataType> Node;    
private:
            const DataType* fValue;
            Node* fNext;
            Node* fPrevious;
            DoubleLinkedNode(): fValue((const DataType*)0){
                fNext = (Node*)0;
                fPrevious = (Node*)0;
            }

这意味着 fValueconst DataType* ,现在我想通过这部分将 stringint 之类的数据类型应用/定义到 fValue

    DoubleLinkedNode( const DataType& aValue ){

        std::cout << "  --  "  << aValue << std::endl;
    }

我很困惑,我必须在那里写什么,为什么?如何将aValue 定义为我的fValue?! (注意:std::cout &lt;&lt; " -- " &lt;&lt; aValue &lt;&lt; std::endl; 仅用于测试)

【问题讨论】:

  • 附注 - 你不需要投 0
  • 不清楚您要做什么。您要打印*fValue吗?

标签: c++ class reference types linked-list


【解决方案1】:

我不太确定你在这里要做什么,但是如果你想用 fValue 指向 aValue 的地址(通过引用传递给构造函数)构造 DoubleLinkedNode,你需要定义你的构造函数 this方式:

DoubleLinkedNode( const DataType& aValue ) : fValue(&aValue) {
        std::cout << "  --  "  << aValue << std::endl;
}

请注意,这样做不是 100% 安全的,因为您可能会不小心使用 rvalue 引用调用此构造函数(为了简化事情:对在函数调用后立即销毁的对象的引用)。例如,以下代码不会引发编译错误:

std::string s = "Hello ";
DoubleLinkedNode<std::string> node = DoubleLinkedNode<std::string>(s + "World");

尽管s + "World" 是一个临时值,在构造函数调用后会立即销毁,现在 fValue 将指向一个无效的内存位置。这很糟糕,因为您在编译期间不会收到任何警告,但您会在运行时遇到一些非常难以调试的行为。

因此,创建一个期望指针而不是引用的构造函数可能会更好:

DoubleLinkedNode( const DataType* aValue ) : fValue(aValue) {
        std::cout << "  --  "  << aValue << std::endl;
}

【讨论】:

    【解决方案2】:

    如果fValue 是一个指针,它需要指向在别处创建的某个变量。那么什么代码负责指向值*fValue 的生命周期?

    如果类需要自己创建值,而fValue确实需要是指针,可以使用newdelete

    template <typename DataType>
    DoubleLinkedNode<DataType>::DoubleLinkedNode( const DataType& aValue )
      : fValue( new DataType(aValue) ), fNext(0), fPrevious(0)
    {}
    template <typename DataType>
    DoubleLinkedNode<DataType>::~DoubleLinkedNode() {
        delete fValue;
    }
    

    但我怀疑如果 fValue 一开始不是指针,设计可能会更好:

    private:
        const DataType fValue;
    
    // Requires a default constructor for DataType.
    template <typename DataType>
    DoubleLinkedNode<DataType>::DoubleLinkedNode()
      : fValue(), fNext(0), fPrevious(0)
    {}
    template <typename DataType>
    DoubleLinkedNode<DataType>::DoubleLinkedNode( const DataType& aValue )
      : fValue(aValue), fNext(0), fPrevious(0)
    {}
    

    【讨论】:

      【解决方案3】:

      由于fValue是一个指针,而DoubleLinkedNode()通过引用获取一个对象,你需要解引用指针,像这样:

      DoubleLinkedNode(*fValue);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-15
        • 1970-01-01
        • 2010-12-12
        • 1970-01-01
        • 1970-01-01
        • 2019-12-28
        • 1970-01-01
        • 2012-01-17
        相关资源
        最近更新 更多