2014-09-24 79 views
1

我想弄清楚如何我可以或为什么我不能访问这个类的成员。首先,我会告诉你什么有用,所以你知道我在想什么,然后我会告诉你我不能做什么。访问另一个类的指针数组的一个类的成员

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

此代码几乎正常工作:

#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

以下是无效的语法:

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();

2

您正以不正确的方式解引用变量。 试试

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

改为。 以同样的方式,第二次尝试,它为你的作品,也已被写入:

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

尝试使用此代码:

cout << firstTestPoint.testclassArray[0]->number << endl; 
相关问题