c++ - 如何传递对象数组?

标签 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;
}

最佳答案

在现代 C++ 中,帮自己一个忙,使用方便的容器类来存储数组,例如 STL std::vector(而不是使用 raw 类似 C 的数组)。

在其他特性中,std::vector 定义了 operator=() 的重载,这使得使用简单的方法将源 vector 复制到目标 vector 成为可能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 ( live 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";
}

关于c++ - 如何传递对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25586997/

相关文章:

c# - 从 dll 调用函数时分配大小无效

c++ - 如何在同一类的公共(public)函数中调用私有(private)类函数(带参数)?

c++ - CMake 需要管理员

c++ - 从数组更改值

c++ - 关于堆清理的 C++ 约定理论,一个建议的构建,是好的做法吗?

c++ - 在 C 中使用 *&*&p 理解复杂的指针和寻址运算符

c++ - 如何找到套接字的IP地址c++/c

java - 在 Java 中加载静态编译的库

c++ - 并行命令模式

python - 在 Python 的 C/C++ 扩展中,返回的 PyObject* 应该具有多少引用计数?