You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++类数组调用成员函数报错:请求成员‘GetSum’于指针类型‘Test*’

问题解决步骤

1. 修复运算符优先级导致的编译错误

你出错的代码行*(test + 0).GetSum()里,成员访问运算符.的优先级高于指针解引用*和加法+,编译器会先尝试对test+0(即test指针)调用.GetSum(),但test是Test*类型,必须用->访问成员,或先正确解引用指针。

你可以用三种写法修复这个错误:

  • 给解引用操作加括号:(*(test + 0)).GetSum()
  • 使用数组下标语法(更直观):test[0].GetSum()
  • 使用指针成员访问运算符:(test + 0)->GetSum()

2. 修复malloc带来的未构造对象问题

这是更严重的潜在问题:malloc仅分配内存,不会调用类的构造函数。直接对malloc分配的内存执行*(test + 0) = Test(1, 2),相当于把临时Test对象赋值给未构造的Test实例,属于未定义行为,可能导致程序崩溃或逻辑错误。

有两种解决方案:

方案A:用new替代malloc(C++推荐做法)

new会自动分配内存并调用构造函数,代码简洁安全:

// 用列表初始化直接构造数组元素
Test *test = new Test[5]{Test(1,2), Test(3,4), Test(5,6), Test(7,8), Test(9,10)};

使用完记得用delete[] test;释放内存。

方案B:用placement new初始化malloc分配的内存

如果必须用malloc,需要用placement new在已分配的内存上手动调用构造函数:

Test *test = (Test*)malloc(sizeof(Test) * 5);
// 在test[0]的内存位置调用构造函数
new (test + 0) Test(1, 2);
// 调用成员函数
int sum = test[0].GetSum();
// 用完后必须手动调用析构函数
test[0].~Test();
free(test);

3. 修复GetSum的逻辑错误

你的Test类构造函数未给ans赋值,GetSum()返回的是未初始化的垃圾值。需要在构造函数里计算ans的值:

Test(int x, int y) {
    this->x = x;
    this->y = y;
    this->ans = x + y; // 新增赋值逻辑
}

也可以用初始化列表写法(更高效):

Test(int x, int y) : x(x), y(y), ans(x + y) {}

最终修复后的完整代码(推荐方案A)

#include <iostream>

using namespace std;

class Test
{
public:  
    Test(int x, int y)
        : x(x), y(y), ans(x + y)
        {}

        int GetSum()
        {
                return ans;
        }

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

int main()
{
        Test *test = new Test[5]{Test(1, 2), Test(3, 4), Test(5, 6), Test(7, 8), Test(9, 10)};

        int sum = test[0].GetSum();
        cout << sum << endl; // 输出3

        delete[] test;
        return 0;
}

内容的提问来源于stack exchange,提问作者SpinRoleDevelop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 05:00:32