【问题标题】:accessing the member of a class of pointer array of another class访问另一个类的指针数组的一个类的成员
【发布时间】:2026-01-11 08:35:02
【问题描述】:

我正试图弄清楚我怎么能或者为什么我不能访问这个类的成员。首先我会告诉你什么是有效的,这样你就知道我在想什么,然后我会告诉你我似乎做不到的。

我能做的是:我有一个有成员的班级。我制作了该类的指针数组并制作了它的新部分(通过循环),这很好。我还可以使用类似的数组创建另一个类,甚至创建新的实例并初始化它们,但是当我尝试访问它们时,我遇到了问题。

这段代码几乎可以正常工作:

#include <iostream>
using namespace std;

class testClass{
    public:
    int number;
};

class testPoint{
    public:
    testClass testInstance;
    testClass *testclassArray[5];
    void makeArray();
    void setToI();
};

void testPoint::makeArray(){
    for (int i = 0; i < 5; i++){
        testclassArray[i] = new testClass;
    }
}

void testPoint::setToI(){
    for (int i = 0; i < 5; i++){
        (*testclassArray[i]).number = i;
    }
}

int main(void){
    testPoint firstTestPoint;
    firstTestPoint.makeArray();
    firstTestPoint.setToI();
//  EXCEPT FOR THIS LINE this is where I have problems
    cout << firstTestPoint.(*testclassArray[0]).number << endl;
    return 0;
}

我知道这应该有效,因为它有效

int main(void){
    testPoint firstInstance;
    firstInstance.testInstance.number = 3;
    cout << firstInstance.testInstance.number << endl;
    // and this works
    return 0;
}

这行得通

int main(void){
    testClass *testPointer[5];
    for (int i = 0; i < 5; i++){
        testPointer[i] = new testClass;
        (*testPointer[i]).number = i; 
    }
    cout << (*testPointer[0]).number << endl; 
    return 0; 
}

那么为什么我不能以同样的方式访问 cout 函数上的成员呢?

【问题讨论】:

    标签: c++ arrays class pointers dereference


    【解决方案1】:

    尝试使用此代码:

    cout << firstTestPoint.testclassArray[0]->number << endl;
    

    【讨论】:

      【解决方案2】:

      以下语法无效:

      cout << firstTestPoint.(*testclassArray[0]).number << endl;
      

      编写您要完成的任务的最常见方式是:

      cout << firstTestPoint.testclassArray[0]->number << endl;
      

      但是,如果你愿意,你也可以写:

      cout << (*firstTestPoint.testclassArray[0]).number << endl;
      

      (第二种方式不太常见。)

      . 运算符用于访问直接对象的成员,例如a.member 其中a 可能被声明为struct A a;-&gt; 运算符用于访问间接对象的成员(也称为对象指针),例如b-&gt;member 其中b 可能被声明为struct B* b = new B();

      【讨论】:

        【解决方案3】:

        您以不正确的方式取消引用变量。 尝试做

        cout << firstTestPoint.testclassArray[0]->number << endl;
        

        相反。 以同样的方式,第二次尝试,它适用于你,也可以写成:

        out << testPointer[0]->number << endl;
        

        【讨论】:

          最近更新 更多