2

我正在创建一个名为 Team 的类。如何让两个对象作为合作伙伴相互指向?这是我迄今为止一直在做的事情。我仅使用布尔数据字段对其进行了测试,并且我知道我的程序的其余部分到目前为止都可以正常工作。

#include <iostream>
using namespace std;

 class Team
{
    public:

    Team();
    Team(bool prac, Team *part);
    Team *partner;
    bool practiced;
    void createPairing (Team *t1, Team *t2);
};


Team::Team()
{
    practiced = false;
    partner = 0;
}

Team::Team(bool prac, Team *part)
{
    practiced = prac;
    partner = part;
}

void Team::createPairing (Team *t1, Team *t2)
{
    t1->partner = t2;
    t2->partner = t1;
}

int main()
{
    Team Harry;
    Team Ron;
    Team *p1 = &Harry;
    Team *p2 = &Ron;
    Team createPairing(p1, p2);

    cout << Harry.partner << endl;
    return 0;
}
4

3 回答 3

0

createPairing应该是static

static void createPairing(Team* t1, Team* t2);

除此之外,问题在于,当您这样做时Team createPairing(p1, p2);,您实际上并没有调用该createPairing函数,而是隐式调用了第二个构造函数 。它正在创建一个被调用并转换为. (编译时应该有一个警告,假设你有警告。)TeamcreatePairingp1bool

在你创建createPairing函数之后static,你会这样称呼它:

Team::createPairing(&Harry, &Ron);
于 2013-03-27T15:44:17.960 回答
0

如果您想有两个参数进行配对,您应该将其设为自由函数(在类之外)。否则我建议省略第一个参数(从对象的角度来看它是“this”)。两者都将有助于防止 magtheridon96 已经提供修复的错误。

void Team::createPairing (Team *other)
{
    partner = other;
    other->partner = this; // here, making the member private and providing a setter would be better
}

或者,作为一个自由函数(使用 setter)

void createPairing(Team& lhs, Team& rhs) // use references to avoid potential pointer issues
{
    lhs.setPartner(&rhs);
    rhs.setPartner(&lhs);
}
于 2013-03-27T16:05:40.263 回答
0
#include <iostream>
using namespace std;

class Team
{ 
    public:

    Team();
    Team(bool prac, Team *part);
    Team *partner;
    bool practiced;
    static void createPairing (Team *t1, Team *t2);
};


Team::Team()
{
    practiced = false;
    partner = 0;
}

Team::Team(bool prac, Team *part)
{
    practiced = prac;
    partner = part;
}

void Team::createPairing (Team *t1, Team *t2)
{
    t1->partner = t2;
    t2->partner = t1;
}

int main()
 {
    Team Harry;
    Team Ron;
    Team *p1 = &Harry;
    Team *p2 = &Ron;
    Team::createPairing(p1, p2);


    return 0;
}
于 2013-03-27T18:58:49.950 回答