如何传递一组对象?

时间:2014-08-30 21:40:33

标签: c++

这里有一个非常简单的程序。我的目标是让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;
}

3 个答案:

答案 0 :(得分:1)

在现代C ++中,帮自己一个忙,并使用方便的容器类来存储数组,例如STL std::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::vectorlive here on 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";
}

答案 1 :(得分:0)

而不是创建A的数组,即&#39; b&#39;在main中,创建一个指向A的指针。然后通过调用getdata()来初始化它。

A *b;

B *x = new B();

b = x->getdata();

答案 2 :(得分:0)

这是一个例子

#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];
相关问题