如何传递对象数组

How can I pass an array of objects?

本文关键字:数组 对象 何传递      更新时间:2023-10-16

这里我有一个非常简单的程序。我的目标是让b等于c,也就是把c的所有内容复制到b中。但我不知道怎么做。getdata()函数返回一个指向对象c数组的指针,但如何使用它将c放入b?

#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
    public:
    A(int i,int j):length(i),high(j){}
    int length,high;
};
class B
{
    private:
    A c[3] = {A(9,9),A(9,9),A(9,9)};
    public:
    A* getdata()
    {
        return c;
    }
};
int main()
{
    A b[3]={A(0,0),A(0,0),A(0,0)};
    B *x = new B();
    cout<< x->getdata() <<endl;
    cout << b[1].length<<endl;
    return 0;
}

在现代C++中,让自己受宠若惊,使用一个方便的容器类来存储数组,如STLstd::vector(而不是使用raw类C数组)。

在其他特征中,std::vector定义了operator=()的过载,这使得可以使用简单的b=c;语法将源向量复制到目的向量。

#include <vector>  // for STL vector
....
std::vector<A> v;  // define a vector of A's
// use vector::push_back() method or .emplace_back()
// or brace init syntax to add content in vector...
std::vector<A> w = v;  // duplicate v's content in w

这可能是对代码的部分修改,使用std::vector(位于codepad上):

#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
    A(int l, int h) : length(l), high(h) {}
    int length, high;
};
class B
{
private:
    vector<A> c;
public:
    const vector<A>& getData() const
    {
        return c;
    }
    void setData(const vector<A>& sourceData)
    {
        c = sourceData;
    }
};
int main()
{
    vector<A> data;
    for (int i = 0; i < 3; ++i) // fill with some test data...
        data.push_back(A(i,i));
    B b;
    b.setData(data);
    const vector<A>& x = b.getData();
    for (size_t i = 0; i < x.size(); ++i) // feel free to use range-for with C++11 compilers
        cout << "A(" << x[i].length << ", " << x[i].high << ")n";
}

不要创建A的数组,即main中的"b",而是创建一个指向A的指针。然后通过调用getdata()对其进行初始化。

A *b;
B *x = new B();
b = x->getdata();

下面是一个示例

#include <iostream>
#include <algorithm>
class A
{
public:
    A( int i, int j ) : length( i ), high( j ){}
    int length, high;
};
class B
{
private:
    A c[3] = {A(9,9),A(9,9),A(9,9)};
public:
    A* getdata()
    {
        return c;
    }
};
int main() 
{
    A b[3] = { A(0,0), A(0,0), A(0,0) };
    B *x = new B();
    A *c = x->getdata();
    std::copy( c, c + 3, b );

    for ( const A &a : b ) std::cout << a.length << 't' << a.high << std::endl;
    delete []x;
    return 0;
}

输出为

9   9
9   9
9   9

您可以使用一个普通的循环来代替标准的算法std::copy。例如

for ( size_t i = 0; i < 3; i++ ) b[i] = c[i];