【问题标题】:The mysteries of an overloaded operator's body超载操作员身体的奥秘
【发布时间】:2013-10-21 06:43:00
【问题描述】:

假设我有以下课程:

树木和树木;

Object Trees 包含一个 Tree 对象数组。

这里是 Trees 和 Tree 类的内容:

Trees.h:

#pragma once

#include "Tree.h"

class Trees
{
private:
    Tree m_Tree[20];
    int iTrees;

public:
    Trees(void) : iTrees(0){}

    Tree GetTree(int i){ return m_Tree[i];}

    void AddTree(Tree tree){ m_Tree[iTrees++] = tree;}

};

树.h:

#pragma once

#include <string>

class Tree
{

private:
    std::string Name;
    bool HasRelatives;

public:
    Tree(void):HasRelatives(0){};

    Tree(std::string name):Name(name), HasRelatives(0){};


    std::string GetName(){ return Name;}

    void SetName(std::string name){ Name = name;}

    bool GetHasRelatives(){ return HasRelatives;}

    void SetHasRelatives(bool alone){ HasRelatives = alone;}


    bool operator == (Tree & tree)
    {
        if(this->GetName() == tree.GetName())
        {
            this->SetHasRelatives(1);

            tree.SetHasRelatives(1);

            return 1;
        }
        return 0;
    }

};

假设我正在使用这样的类 (main.cpp):

#include <iostream>
#include "Trees.h"


int main()
{
    Trees Trees;

    Trees.AddTree(Tree("Oak"));

    Trees.AddTree(Tree("Oak"));


    if(Trees.GetTree(0) == Trees.GetTree(1))
    {

        std::cout<<"Trees are the same" << std::endl;

        if(Trees.GetTree(1).GetHasRelatives() == 1)
            std::cout<<"Tree has relatives" << std::endl;
    }

    return 0;
}

根据我目前的理解,程序应该输出“树有亲戚”,因为第二棵树( Trees.GetTree(1) )是通过引用传递的,因此在 == 操作符的主体内部所做的任何更改都应该在它外部可见...

我哪里错了?

【问题讨论】:

  • 多么美丽的问题名称。
  • 好吧,我可能用过头了...

标签: c++ function class reference operator-overloading


【解决方案1】:

虽然 operator== 改变其参数的语义值得怀疑,但您的具体问题是您正在从 GetTree 返回副本:

Tree GetTree(int i){ return m_Tree[i];}

因此副本会在您应用== 时被修改,然后它们会被丢弃。当您再次调用GetTree 时,新副本当然不会被修改。

你需要的是

Tree& GetTree(int i){ return m_Tree[i];}

能够修改存储在m_Tree[i]中的树。

【讨论】:

  • 非常感谢您的快速回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多