首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >间接需要指针操作数和预期的表达式错误。

间接需要指针操作数和预期的表达式错误。
EN

Stack Overflow用户
提问于 2015-07-01 23:13:17
回答 1查看 936关注 0票数 0

我不断地收到类似于以下错误的错误:

代码语言:javascript
复制
pitstop.cpp:36:23: error: indirection requires pointer operand

        ('double' invalid)

         cost = UNLEADED * gallons;

                          ^ ~~~~~~~

pitstop.cpp:40:14: error: expected expression

                    cost = SUPER * gallons;                               ^
代码语言:javascript
复制
#include <iostream>
#include <iomanip>
using namespace std;

#define UNLEADED 3.45;
#define SUPER {UNLEADED + 0.10};
#define PREMIUM {SUPER + 0.10};

/* 
    Author: Zach Stow
    Date: 
    Homework 
    Objective:
*/

double cost, gallons;
string gasType, finish, stop;

int main()
{
    for(;;)

    {

        cout <<"Hi, welcome to Pitstop.\n"; 
        cout <<"Enter the type of gas you need:";
        cin >> gasType; 
        cout << endl;

        cout <<"Enter the amount of gallons you need:";
        cin >> gallons;
        cout << endl;

        if(gasType == "finish" || gasType == "stop")break;

        else if(gasType == "UNLEADED")
        {
            cost = UNLEADED * gallons;
        }
        else if(gasType == "SUPER")
        {
            cost = SUPER * gallons;
        }   
        else if(gasType == "PREMIUM")
        {
            cost = PREMIUM * gallons;
        }

    }   
    cout <<"You need to pay:$" << cost << endl;

    return(0);

}
EN

回答 1

Stack Overflow用户

发布于 2015-07-02 00:31:52

错误的原因是#define指令末尾的分号。

您还使用了不正确的括号类型,请尝试以下操作:

#define UNLEADED 3.45 #define SUPER (UNLEADED + 0.10) #define PREMIUM (SUPER + 0.10)

注意,当您使用#define指令时,下面的#define将被替换为您的代码。在本例中,在预处理器运行之后,代码如下所示:

else if(gasType == "UNLEADED") { cost = UNLEADED 3.45; * gallons; } else if(gasType == "SUPER") { cost = {UNLEADED + 0.10}; * gallons; }

else if(gasType == "PREMIUM") { cost = PREMIUM {SUPER + 0.10}; * gallons; }

获得indirection requires pointer operand错误的原因是编译器试图解释以下语句:

* gallons;

因为*运算符只有一个参数,所以它被解释为指针取消引用,幸运的是,对您来说,gallons变量不是指针类型。如果加仑被声明为指针类型,即double cost, *gallons;,而cin不存在,那么代码将编译,但不会按您的预期执行,可能会抛出一个分段错误。

使用# defined定义的宏可能非常强大,而且非常危险。在c++中通常有更好的方法来实现目标。在这种情况下,UNLEADEDSUPER_UNLEADEDPREMIUM可以声明为const double类型。

const double unleaded = 3.45; const double super = unleaded + 0.10; const double premium = super + 0.10;

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31174020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档