返回指向数组的指针

Return pointer to array

本文关键字:指针 数组 返回      更新时间:2023-10-16

我正在尝试为我的函数原型返回指向数组的指针。

class NAV                  
{
    string date;
    float nav;
public:
    NAV(const string&);  
};
const int HistorySize = 300;
class MutualFund
{
    string ticker;
    NAV* history[HistorySize];
public:
    MutualFund(const string& ticker_, const string& historyFile);
    ~MutualFund();
    NAV** getArray() const{return history;}
    void report() const;
};

对于 NAV** getArray() const{return history;},我收到一个编译器错误:

错误:从"NAV* 常量*"到"导航**"的转换无效 [-允许]

有什么想法吗?

NAV** getArray() const{return history;} const中表示程序员承诺调用此函数不会导致MutualFund状态发生变化。通过返回一个非常量指针,NAV** ,你打开了通过使用返回的指针来更改状态的可能性。编译器不允许这样做,并告诉您它只能返回指向常量数据的指针:NAV* const*

您的 getter 是一个 const 方法,因此在其执行过程中,所有数据成员也都被视为 const。 这就是为什么转换错误说它正在从 const 转换为非 const,因为您的返回值是 non-const。