C ++语义问题,const value_type到指针*

时间:2012-05-03 08:42:40

标签: c++ arrays

我正在尝试使用此C ++方法返回b2Fixture实例的数组。它迭代了一系列JRContact实例,其定义如下:

struct JRContact {
    b2Fixture *fixtureA;
    b2Fixture *fixtureB;
    bool operator==(const JRContact& other) const
    {
        return (fixtureA == other.fixtureA) && (fixtureB == other.fixtureB);
    }
};

n.b。我对C ++完全陌生,不要犹豫提到我在该代码中可能做过的奇怪事情; - )

以下无法编译(MacOS上的XCode编译器),请参阅注释中的错误:

id AbstractContactListener::getFixturesOfTypeCollidingWithFixture(b2Fixture *fix, int type){

    std::vector<b2Fixture> fixtures;

    std::vector<JRContact>::iterator ct;
    JRContact contact;

    for (ct = _contacts.begin(); ct != _contacts.end(); ct++){

        contact = *ct;

        if ( 
                ( (fix == contact.fixtureA) || (fix == contact.fixtureB) ) &&
                ( contactContainsType(contact, type) )
            ){

            if (fix == contact.fixtureA) {

                // error: Semantic Issue: Reference to type 'const value_type' (aka 'const b2Fixture') could not bind to an lvalue of type 'b2Fixture *'

                fixtures.push_back(contact.fixtureB);
            }

            else {

                // error: Semantic Issue: Reference to type 'const value_type' (aka 'const b2Fixture') could not bind to an lvalue of type 'b2Fixture *'
                fixtures.push_back(contact.fixtureA);
            }
        }
    }

    // error: Semantic Issue: No viable conversion from 'std::vector<b2Fixture>' to 'id'
    return fixtures;
}

谢谢你的时间!

3 个答案:

答案 0 :(得分:2)

更改:

std::vector<b2Fixture> fixtures;

到:

std::vector<b2Fixture *> fixtures;

关于返回类型,您可以将其更改为void*std::vector<b2Fixture *> *并使用:return &fixtures;

但要注意你的向量是本地的,所以分配它不返回指向无效位置的指针。 (并且当你使用它时,请记得释放它。)

答案 1 :(得分:1)

目前还不是很清楚你想做什么,但问题是你告诉编译器AbstractContactListener::getFixturesOfTypeCollidingWithFixture将返回id而你返回std::vector<b2Fixture>

从函数的名称,我想您可能想要返回vector,因此请将签名更改为:

std::vector<b2Fixture> AbstractContactListener::getFixturesOfTypeCollidingWithFixture
                                                      (b2Fixture *fix, int type)

当你应该推动对象时,你也在向量中推送指针:

fixtures.push_back(*(contact.fixtureB));

答案 2 :(得分:1)

向量fixtures包含b2Fixture个实例,但contact.fixtureAb2Fixture*

或者:

  • 取消引用它:

    fixtures.push_back(*(contact.fixtureA)); // Same for 'fixtureB'.
    

  • 更改fixtures的类型:

    std::vector<b2Fixture*> fixtures;
    

函数返回类型与实际返回的内容之间也存在不匹配。如果要返回fixtures,请使返回类型与fixtures的类型匹配。