【问题标题】:Obtaining the index-value of a pointer class member list encapsulated by another class member which is a pointer获取由另一个类成员封装的指针类成员列表的索引值,该类成员是一个指针
【发布时间】:2012-01-20 20:20:12
【问题描述】:

这个对我来说有点奇怪。

我有一个指向类成员 (mGeometry) 的指针,而该类成员又持有指向 QList< GLushort > 数据成员 (mFaces) 的指针。我正在尝试通过 Cube 类获取 mFaces 的索引。

因此,更简化的版本如下所示:

struct Geometry
{   
    Geometry( void );
    ~Geometry( void );
    void someFunc( void );
    QList< GLushort > *mFaces;
};

class Cube
{   
 public:
    Cube( void );
    ~Cube( void );
    void anotherFunc( void );
    Geometry *mGeometry;
};

假设在anotherFunc,我们正在尝试执行以下操作:

GLushort *indeces = new GLushort;

*indeces = ( *mGeometry ).mFaces[ 0 ];

错误

error: cannot convert ‘QList<short unsigned int>’ to ‘GLushort {aka short unsigned int}’ in assignment

所以,我们尝试:

*indeces = mGeometry->( *mFaces )[ 0 ]; //which, is originally how I've accessed pointers-to-containers' indexes.

错误

error: expected unqualified-id before ‘(’ token

error: ‘mFaces’ was not declared in this scope

当然还有显而易见的:

*indeces =  mGeometry->mFaces[ 0 ];

错误

error: cannot convert ‘QList<short unsigned int>’ to ‘GLushort {aka short unsigned int}’ in assignment

几何构造函数

Geometry::Geometry( void )
    : mFaces( new QList< GLushort > )
{
}

我在这里做错了什么吗?如果不是,那么获取指向mFaces的指针的索引的正确方法是什么?

【问题讨论】:

    标签: c++ arrays qt pointers indexing


    【解决方案1】:

    因为mFaces 是一个指针,所以你必须用-&gt; 取消引用mGeometry,然后用* 取消引用mFaces,然后使用QList&lt;&gt;operator[] 来获取数字:

    *indeces = (*mGeometry->mFaces)[0]; // note that * has lower precedence than ->
                                        // so this is like (*(mGeometry->mFaces))[0]
    

    这有点奇怪,因为[0]* 做同样的事情。指针类型上的索引,例如x[i],遵循公式*(x + i),因此您也可以这样做以获得相同的效果(但不要):

    *indeces = mGeometry->mFaces[0][0]; // or *indeces = (*mGeometry).mFaces[0][0];
    

    (*(mFaces + 0))[0]相同,与(*mFaces)[0]完全相同。

    这也是您尝试执行此操作时收到错误 cannot convert ‘QList&lt;short unsigned int&gt;’ to ‘GLushort’ 的原因

    ( *mGeometry ).mFaces[ 0 ];
    

    因为( *mGeometry ).mFaces[ 0 ];(同样相当于上面的*mGeometry-&gt;mFaces)为您提供QList&lt;GLushort&gt;,而您必须使用QList&lt;&gt;operator[] 来获取您的数据。

    现在对于一些完全不相关的东西,你拼错了 indices :)

    【讨论】:

    • 啊,谢谢。诚然,我是从网上找到的一个文件(render.cpp - 也许你听说过?)中产生的,并改变了一些东西以提高效率。再次,我很感激。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    相关资源
    最近更新 更多