重新定义运算符的麻烦+(c ++)

时间:2013-06-16 12:00:11

标签: c++ arrays class object redefine

class Community
{
private:
    char* Name;
    char foundationDate[11];
    Person founderPtr;
    int maxMembersCount;
    int membersCount;
    Person* members;
    static int communitiesCount;
public:

.
.
.
Person* operator+(Community&); // operator + prototype (must return array of members)
};

Person* Community::operator+(Community& other)
{
Community temp("temp","12.11.1993",other.getFounder());
Person* ptr;
    for(int i = 0 ; i < this->getMembersCount() ; i++)
{
        for(int j = 0 ; j < other.getMembersCount() ; j++)
    {

        if(strcmp(this->members[i].getEGN(),other.members[j].getEGN()) == 0)
        {
            temp.addMember(other.members[j]);
        }
    }
}
ptr = temp.getMembers();
return ptr;
}

如果我在函数中cout<< ptr[i];我可以看到一切正常,但是当我尝试时:

 Community S("obshnost","12.11.2010",A);
Community R("community","11.10.2011",B);
S.addMember(C);
S.addMember(Z);
R.addMember(C);


Person* ptr = S+R;
 for(int i = 0 ; i<2 ; i ++)
{
cout<<ptr[i];
 }

我看到搞砸了结果......如果有人知道我应该寻找什么,我会感激:)

1 个答案:

答案 0 :(得分:0)

如果没有看到你的其他源代码,我无法说肯定,但我猜你的+运算符正在返回一个已经释放的内存指针。