【问题标题】:C++ object reference instead of copyC++ 对象引用而不是复制
【发布时间】:2013-09-21 11:26:34
【问题描述】:

这很好用:

udtCandidate firstCand;
firstCand=uSeqs[i].Candidates.front();

这将创建 udtCandidate 的副本。

但我需要引用它,而不是副本。

然而

udtCandidate firstCand;
firstCand=&uSeqs[i].Candidates.front();

不起作用。 编译器告诉我没有二元运算符“=”接受“udtCandidate *”类型的右手操作数。

有人知道我做错了什么吗?

声明如下:

struct udtCandidate
{
    udtJoinFeatures JoinFeaturesLeft;
    udtJoinFeatures JoinFeaturesRight;
    udtByteFeatures ByteFeaturesLeft;
    udtByteFeatures ByteFeaturesRight;
    int iHPUnitIDLeft;
    int iHPUnitIDRight;
    double targetCost;
    vector<unsigned long>bestPath;
    double bestPathScore;
    bool hasAncestor;
};
struct udtCandidateSequence
{
    double Score;
    vector<udtCandidate>Candidates;
};

【问题讨论】:

    标签: c++ windows object reference


    【解决方案1】:

    要存储引用而不是值,您必须创建一个引用变量:

    udtCandidate& firstCand = uSeqs[i].Candidates.front();
    

    像您一样使用&amp; 意味着地址运算符,这反过来将类型更改为指针。

    【讨论】:

    • 哦,好的。看来我必须在一行中声明和分配它。我尝试声明 udtCandidate& firstCand;在一行中,并在下一行中分配它,但这不起作用...
    • 那是因为你不能有一个空的参考。我建议您在 C++ 书中阅读有关该主题的内容。此外,一行中的初始化是一种很好的编程习惯。
    猜你喜欢
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多