重载操作员身体的奥秘

时间:2013-10-13 16:51:42

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

假设我有以下几个类:

树木和树木;

Object 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;}

};

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;
}

根据我目前的理解,程序应该输出“Tree has relatives”,因为第二个Tree(Trees.GetTree(1))是通过引用传递的,因此在==运算符的主体内部进行的任何更改都应该在其外部可见...

我哪里错了?

1 个答案:

答案 0 :(得分:3)

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

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

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

您需要的是

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

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