【问题标题】:pointer to an array created from another struct (not sure if tha'ts correctly worded)C++指向从另一个结构创建的数组的指针(不确定措辞是否正确)C++
【发布时间】:2015-08-22 14:23:50
【问题描述】:

我在尝试从 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;  

我已经突出显示了从 struct PhoneCall 创建的 PhoneCall。

我需要解决函数

int GetTotalHours(Bill&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 类型的原因。

我对编程非常陌生,并且已经跳入深渊,但希望您能提供帮助:)

【问题讨论】:

  • 我知道你的两个结构是如何相互关联的,但我仍然不知道你想要做什么或者你所说的“指向两种不同类型的指针”是什么意思
  • 不确定你在问什么。请澄清。
  • 不清楚你在问什么
  • 嗨@Giorgi 我已经编辑了我的问题,希望它能让你更清楚地理解我的问题。
  • @muppetblues 你不应该使用int 你应该使用double 作为total_hours,否则你会看到integer division

标签: c++ arrays pointers struct


【解决方案1】:

根据您的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; });
}

【讨论】:

  • 我对拙劣的提问表示歉意。请让我澄清一下。该计划的主要目的是获得两个最便宜的电话费计划。还有 2 个结构,但为简单起见,我将它们排除在外。
  • 感谢您的回答。我确实尝试了类似的东西,我也尝试了你的代码,但我得到的只是 001A11EF。看起来像一个地址。有什么遗漏吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 2017-07-13
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
相关资源
最近更新 更多