访问另一个类的指针数组的成员

时间:2014-09-24 06:02:49

标签: c++ arrays class pointers dereference

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

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

此代码几乎正常工作:

#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功能上的成员?

3 个答案:

答案 0 :(得分:3)

以下是无效的语法:

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

最常见的写作方式是:

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

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

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

(第二种方式不常见。)

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

答案 1 :(得分:2)

您正以错误的方式取消引用该变量。 尝试做

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

代替。 同样,第二次尝试也可以写成:

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

答案 2 :(得分:0)

尝试使用此代码:

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