1

大家好,我对“->”运算符有疑问。这是我的代码:并OfferingPair * weeklySchedule ;Schedule类中清除,而 OfferingPair 在头文件中清除。

struct     OfferingPair
{
  Offering     * off     ;
  OfferingPair * nextOff ;

}


Schedule::Schedule ()
{
    this->weeklySchedule=new OfferingPair[5];

    for(int i=0;i<5;i++)
    {
        weeklySchedule[i]->off=NULL;
        weeklySchedule[i]->nextOff=NULL;
    }   
}

并且因为:

weeklySchedule[i]->off=NULL;
weeklySchedule[i]->nextOff=NULL; 

我收到一条错误消息:

base operand of ‘->’ has non-pointer type ‘OfferingPair’

但是weeklySchedule[i] 是一个指针,为什么我不能使用“->”?提前谢谢。

4

3 回答 3

14

weeklySchedule[i]返回对象本身,而不是指针,所以你必须使用.

weeklySchedule[i].off=NULL;
weeklySchedule[i].nextOff=NULL;

我建议您将代码修改为:

std::vector<OfferingPair> weeklySchedule

尽管。这是 RAIIght (c) 要做的事情。

于 2012-10-22T17:37:08.220 回答
0

The array index operator is basically defined as follows:

a[b] = *(a + (b))

The -> operator is basically defined as follows:

a->b = (*a).b

So when you write:

weeklySchedule[i]->off=NULL;

You are writing this:

(*(*(weeklySchedule + i))).off=NULL;

Notice how you are dereferencing the pointer twice. Clearly this is incorrect!

于 2012-10-22T18:23:58.257 回答
0

Others already pointed out the problem of -> vs. dot (.) syntax.

But I'd like to elaborate a bit on other sides.

Since you are initializing your OfferingPair::off and nextOff data members to NULL, maybe this work should be done inside OfferingPair default constructor:

struct OfferingPair
{
  ....

  OfferingPair()
    : off(NULL)
    , nextOff(NULL)
  {
  }
};

And you can just use a std::vector instead of a raw C-like array to store instances of the above structure. Add a data member to your Schedule class like this:

  std::vector<OfferingPair> m_weeklySchedule;

And then in the default constructor create a std::vector of 5 items:

Schedule::Schedule()
  : m_weeklySchedule(5)
{
}

Note how your code is simplified.

Note also that you don't need an explicit delete[] in your destructor to release the array dynamically allocated memory: std::vector's destructor will be automatically called and will take care of that.

Moreover, the compiler generated copy constructor and copy operator= will do the right thing with member-wise copy (calling the corresponding std::vector copy operations), instead with a raw C-like array you have to write proper code for copy constructor and operator= (or ban them, declaring them private).

EDIT: You seem to have edited your original post adding new code, in particular some sketch of the OfferingPair data structure:

struct OfferingPair
{
  Offering     * off;
  OfferingPair * nextOff;
};

The fact that you have a pointer to the next OfferingPair inside OfferingPair makes me think that maybe you just need a linked list of Offering's? Unless this is a learning exercise for linked lists, maybe you just need a std::list<Offering>, or a C++11 std::forward_list<Offering>?

于 2012-10-22T17:55:35.290 回答