c++ error:request for member 'GetSum' in test ',which is of pointer type 'Test*'(maybe you meant to use '->'?)

pinkon5k  于 2023-05-02  发布在  其他
关注(0)|答案(1)|浏览(289)

我正在学习如何使用Class创建数组。我使用malloc创建了一个名为test的ptr数组。但是当我想使用数组中的值的函数时,我得到了一个错误:error:request for member 'GetSum' in test ',which is of pointer type 'Test*'(maybe you meant to use '-〉'?)

#include <iostream>
#include <cstdlib>

using namespace std;

class Test
{
public:  
    Test(int x, int y)
        {
                this->x = x;
                this->y = y;
        }

        int GetSum()
        {
                return ans;
        }

private:
        int x;
        int y;
        int ans;
};

int main()
{
        Test *test = (Test*)malloc(sizeof(Test) * 5);

        *(test + 0) = Test(1, 2);
        int sum = *(test + 0).GetSum(); /* ERROR HERE */

        return 0;
}
zdwk9cvp

zdwk9cvp1#

问题是由于operator precedence的规则,operator.的优先级高于operator*。这意味着表达式*(test + 0).GetSum()被***分组为***(或等价物)编写:

//this is equivalent to what your wrote
*( (test + 0).GetSum() )
解决方案

解决此错误,您可以显式使用*(test + 0)周围的括号来覆盖此优先级,如下所示:

//--------v-----------v-------------> works now 
int sum = (*(test + 0)).GetSum();

Working demo
另外,我建议在使用C++时使用new而不是malloc

相关问题