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