【问题标题】:How to create a class that holds array of objects of another class , how to manipulate the other class private attributes如何创建一个包含另一个类的对象数组的类,如何操作其他类的私有属性
【发布时间】:2016-11-03 13:45:14
【问题描述】:
// 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);
}

【问题讨论】:

  • 请在将来为您的代码附上一些文字。
  • 具体遇到了什么问题?
  • “如何操作其他类的私有属性”你可能需要公共方法来操作私有属性。
  • 您不能操作其他类的私有数据。这就是private 的全部意义所在。如果您想从班级外部操纵成员,请不要将其设为私有。 (嗯,有friend,但这仅适用于特殊情况)
  • 你为什么不用std::vector

标签: c++ arrays class pointers


【解决方案1】:

首先,要添加到数组中,您可以只依赖隐式声明的复制赋值运算符,它对所有字段进行浅拷贝:

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() 读取数据(通过其副本)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多