如何创建一个类来保存另一个类的对象数组,如何操作其他类的私有属性

How to create a class that holds array of objects of another class , how to manipulate the other class private attributes

本文关键字:何操作 属性 数组 其他 操作 保存 创建 何创建 一个 另一个 对象      更新时间:2023-10-16
// this is the first point class header 
class Point : public CWaypoint{
public:             //temporarily
    string m_description;
public:
    Point();
    virtual ~Point();
    void print();
    Point(string name, string description, double latitude,  double longitude);
    void getAllDataByReference( string& name,string& description, double& latitude,double& longitude);
};

// This is the database class header
class Database 
{
private:                    
    Point m_POI[10];      // Point is the other class
    int m_noPoi;
public:
    Database();
    virtual ~Database();
    void addPoI(string name,string description,double latitude,double longitude);
    Point * getPointerToPoi(string name);
}

首先,要添加到数组中,您可以依赖于隐式声明的复制赋值操作符,该操作符对所有字段进行浅层复制:

void Database::addPoI(string name,string description,double latitude,double longitude) {
    if (m_noPoi >= 10) // handle error
    m_POI[m_noPoi++] = Point(name, description, latitude, longitude);
}

由于数据是私有的,你不能直接访问它(忽略"友"船)。但是,您可以通过point::getAllDataByReference()读取数据(通过它的副本)。