0

我将尝试首先解释我的情况。我有一个里面有结构的类和这个容器类的数组

class A
{
    struct B
    {
        int I;
        B *next;
    };

    B *objOfB; //Array of structures
    B *lastB;  //Pointer to last objOfB element

public:
    //Method for adding values to objOfB
    void addB(int i)
    {
        B *temp = new B;
        temp->I = i;
        temp->next = NULL;
        if(ing == NULL)
        {
            last = temp;
            objOfB = temp;
        }
        else
        {
            last->next = temp;
            last = temp;
        }
    }
};

对象的数组在某些函数文件中使用

A * objA = A[100];

我想不通的是如何处理objOfB. 有一个简单的例子,它将从开始到结束objOfB

for (B *temp = objOfB; temp != NULL; temp = temp->next) {
  cout << temp->I << endl;
}

我想在函数文件中执行这个循环,但我想不出不会返回所有的方法objOfB(它用于循环的第一部分B *temp = objOfB;)。以下是我为执行此循环而创建的方法:

B listOfBs() { return *objOfB;  }
B toNextB() { return *objOfB->next; }
bool noLastB(){ return objOfB->next != NULL; }

它是如何工作的,它可以在循环中使用:

for (B *temp = listOfBs(); noLastB(); temp = toNextB()) {
  cout << temp->I << endl;
}

但是我知道这三种方法都不适合这个循环。所以我需要一些方法来返回值,另一种方法来告诉应该读取下一个值......希望不是更清楚我想要实现的目标。

如何使用方法传递结构值的容器类动态数组?

4

1 回答 1

0

From what I understand, you have the class A (that represents a wrapper of singly-linked list) and this simple struct B nested in it :

struct B
{
    int I;
    B *next;
};

and you want the class A to also provide an interface, that would provide the simpler way of iterating through this list.

At first, this data member is very confusing:

B *objOfB; //Array of structures

since you are treating it as a pointer to the first element. Good start would be to rename it to: B *head; So now each instance of B can point to the next element and you have the pointer to the head, last element is the element with next equal to NULL, you don't need B *lastB;.

Then you will realize that methods you tried to provide don't make much sense:

B listOfBs() { return *head;  }
B toNextB() { return *head->next; }
bool noLastB(){ return head->next != NULL; }

there is no reason why these methods should return by value and since the definition of struct B will have to be visible to the caller anyway. For the sake of KISS principle, just make head the public data member of A and rename A to more meaningful name, for example MyList. Then let the caller do this:

MyList list;
...
for (B* b = list.head; b != NULL; b = b->next) {
    ...
}
于 2013-03-22T10:46:59.387 回答