0

could someone please tell me what I need to do in order to create an array of objects in a function (other than in the main function).

I will try to explain by making up some sort of example...

Let's say I have a program named TimeScheduler.cpp that implements the class Schedule.h (and I have the implementation in a separate file Schedule.cpp where we define the methods).

In the declaration file we have declared two constructors

  Schedule(); //the default

and

  Schedule(int, int, int);//accepts three arguments

to get to the point--let's say in the main program file TimeScheduler.cpp we created our own functions in this program apart from the functions inherited from the class Schedule. so we have our prototypes listed at the top.

 /*prototypes*/

  void makeSomeTime();

etc.....

we have

 main(){ 


//etc etc...
 }

we then define these program functions

    void makeSomeTime(){
      //process
    }

let's say that inside the function makeSomeTime(), we would like to create an array of Schedule objects like this

    Schedule ob[]={ 
       summer(5,14, 49), 
       fall(9,25,50)
    };

what do I have to do to the function makeSomeTime() in order for it to allow me to create this array of objects. The reason I ask is currently i'm having difficulty with my own program in that it WILL allow me to create this array of objects in main()....but NOT in a function like I just gave an example of. The strange thing is it will allow me to create a dynamic array of objects in the function..... like

   Schedule *ob = new Schedule[n+1];
   ob[2]= Schedule(x,y,z);

Why would it let me assign to a non-dynamic array in main(), but not let me do that in the function?

4

2 回答 2

2

这是不正确的:

 Schedule ob[]={ 
       summer(5,14, 49), 
       fall(9,25,50)
    };

似乎正在尝试引入 3 个新名称:

  1. ob,这是一个Scedules的数组
  2. summer,这是一个Schedule
  3. fall,这是一个Schedule

你不能像那样介绍summerfall作为新名字。也许这只是一个错字,你的意思是:

Schedule ob[]={ 
   Schedule(5,14, 49), 
   Schedule(9,25,50)
};

...这非常好,并且可以存在于以下函数中:

void make_schedule()
{
    Schedule ob[]={ 
       Schedule(5,14, 49), 
       Schedule(9,25,50)
    };
}

但是现在你有另一个问题——你的make_schedule函数返回了void。您在其中创建的Schedule数组make_schedule被创建,然后被丢弃。如果你想从一个函数返回一个数组,最好的办法是使用 a vector,然后返回:

std::vector<Schedule> make_schedule()
{
    Schedule ob[]={ 
       Schedule(5,14, 49), 
       Schedule(9,25,50)
    };

    const size_t num_obs = sizeof(ob)/sizeof(ob[0]);
    std::vector<Schedule> ret;
    std::copy( &ob[0], &ob[num_obs], std::back_inserter(ret));

    return ret;
}

一个更差的选择是使用动态分配来分配你的数组,并返回一个指向第一个元素的指针。在这种情况下,使用时new []需要注意的是,您只能使用默认构造函数。

于 2012-06-18T21:39:54.347 回答
0

我决定不使用向量,而是使用 unordered_map。我没有意识到当你在 C++ 中“命名”一个对象时,你并没有真正给它一个名字……它只是用作一种临时引用。如果要使用名称,最好使用名称作为集合中的一种键值。喜欢:

字符串食物名称;

foodname = "蛋糕";

[食品名称,10.95]

foodname = "面包";

[食品名称,5.75]

我在http://msdn.microsoft.com/en-us/library/bb981993.aspx上找到了有关 unordered_map 的帮助

于 2012-06-19T13:29:00.257 回答