传递一个动态的对象数组来运行 [英] Pass a dynamic array of objects to function

查看:104
本文介绍了传递一个动态的对象数组来运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习c ++。所以我知道一种方法,通过它你发送的东西功能,然后工作,如果它是按值调用,但实际上它是通过引用调用。例如

  void myFUNC(string& x)

现在,我有一个动态创建的对象数组。我想传递数组以像上面的方法一样工作。这是代码片段

  City * p = new City [number]; //指向动态类对象数组的指针

//函数原型
void list_cities(int number,City p []){
for(int i = 0; i< number; i ++){
cout<< p [i] .get_name()<< endl;


$ / code $ / pre

解决方案

阵列默认为 转换为指针,然后将其作为参考传递。因此,没有明确规定通过引用传递数组。也就是说,

  void list_cities(int number,City& p [])

不是 p [] 作为参考传递,但是使得



代码:

 

(int i = 0; i< number; i ++)
{
cout< < p [I] .get_name()<< ENDL;



int main()
{
City * p = new City [number];
list_cities(number,p);
delete [] p;
}


I am in the process of learning c++. So i know a method by which you send something to function and then work as if it was call by value but actually it is call by reference. For example

void myFUNC(string& x)

Now, I have a dynamically created array of objects. I want to pass the array to function like a method above. Here's the code snippets

City *p = new City[number]; // pointer to dynamic array of class objects

//function prototype
void list_cities(int number, City p[]){
    for(int i=0; i<number; i++){
        cout<<p[i].get_name()<<endl;
    }
}

解决方案

Arrays are by default converted to pointers, which are then passed as reference. So, there is no provision for explicitly passing arrays by reference. That is,

void list_cities(int number, City &p[])

is not p[] being passed as reference, but makes p[] an array of references.

Code:

void list_cities(int number, City p[])
{
    for(int i=0; i<number; i++)
    {
        cout<<p[i].get_name()<<endl;
    }
}

int main()
{
    City *p = new City[number];
    list_cities(number,p);
    delete[] p;
}

这篇关于传递一个动态的对象数组来运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆