所以我在C ++中有两个不同的类,
#ifndef A_H
#define A_H
class A
{
public:
...
private:
static const int MAX = 52;
int a_array[MAX];
};
#endif // A_H
我想把那个数组用到另一个类......但是我想知道我是不是只能返回一个数组,我应该怎么做?我是否被迫在B类中创建另一个数组并复制它?
这将是第二类......
#include "A.h"
#ifndef B_H
#define B_H
class B
{
public:
...
void createNewDeck("here would be the array, or the object I'd like to input to use the array inside");
private:
static const int min = 5;
int a_array[min]
};
#endif // B_H
编辑:我希望它们不同,我希望有一个适用于A类数组的B方法。我会有一个B方法,从该数组中获取一些值;这样的事情,所以你们可以得到我的想法。
void B::createNewDeck(const A &a){
a_array[0] = a.a_array[5];
a_array[3] = a.a_array[48];
}
感谢您的帮助!
答案 0 :(得分:1)
数组只是指向一段数据的指针。但是你需要非常清楚自己想要什么。您是否要复制数据并使用单独的副本进行播放?或者您希望第二个类能够完全访问原始文件吗?
您可以在函数中返回指针,也可以将成员变量作为公共或朋友访问。
答案 1 :(得分:0)
create a method in public int Array(int index) and return the value to your desired
like:
class B
{
public:
void createNewDeck("here would be the array, or the object I'd like to input to use the array inside");
private:
static const int min = 5;
int a_array[min]
// Method to return value outside
public:
int Array(int Index)
{
return Index>min ?-1:a_array[Index-1];
}
};
答案 2 :(得分:0)
最简单的方法是让B
成为A
的朋友。这样B
就可以访问A
private
成员。
class B; // forward declare B to make it visible in A's scope. Important
class A
{
private:
static const int MAX = 52;
int a_array[MAX];
friend class B; // !!
//friend B; // if you have C++11
};