指向从另一个结构创建的数组的指针(不确定措辞是否正确)C++

pointer to an array created from another struct (not sure if tha'ts correctly worded)C++

本文关键字:是否 C++ 不确定 指针 另一个 结构 创建 数组      更新时间:2023-10-16

我有一个问题,试图从2结构体检索信息。第一个是:

struct PhoneCall{
    std::string date;       
    int minutes;            
    int seconds;

第二个是:

struct Bill{
    Customer holder;                            
    Plan plan;
    PhoneCall callList[BILL_CALL_LIST_SIZE];                                
    int count;                                  
    long durationSeconds;                       
    int block;  

我已经突出显示了PhoneCall,它是从结构体PhoneCall创建的。

我需要解函数

int GetTotalHours (Bill&比尔)

我发现很难创建从bill到Phonecall的指针。我得到一个消息说没有转换存在。

我已经尝试了下面的代码,这是善意提供的解决方案。(我使用了类似的东西,但它似乎返回一个地址001A11EF)。

int total_hours = 0;
        for (int call = 0; call < BILL_CALL_LIST_SIZE; ++call)
        {
            total_hours += bill.callList[call].minutes / 60+ bill.callList[call].seconds / 3600;
        }
        return total_hours;

后面还有一个函数返回总分钟数,这就是GetTotalHours函数为int类型的原因。

我对编程非常陌生,已经跳入了深渊,但希望你能帮助我:)

基于struct,如果给定Bill,则GetTotalHours可能类似于

double GetTotalHours(Bill const& bill)
{
    double total_hours = 0.0;
    for (int call = 0; call < BILL_CALL_LIST_SIZE; ++call)
    {
        total_hours += bill.callList[call].minutes / 60.0 + bill.callList[call].seconds / 3600.0;
    }
    return total;
}

如果您可以访问c++ 11,则可以将其写成

#include <iterator>
#include <numeric>
double GetTotalHours(Bill const& bill)
{
    return std::accumulate(std::begin(bill.callList),
                           std::end(bill.callList),
                           0.0,
                           [](double total_hours, PhoneCall const& call){ return total_hours + bill.callList[call].minutes / 60.0 + bill.callList[call].seconds / 3600.0; });
}