间接寻址需要指针操作数和预期的表达式错误
indirection requires pointer operand and expected expression errors
我不断收到类似以下的错误:
pitstop.cpp:36:23: error: indirection requires pointer operand
('double' invalid)
cost = UNLEADED * gallons;
^ ~~~~~~~
pitstop.cpp:40:14: error: expected expression
cost = SUPER * gallons; ^
#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);
}
不是c++
专家,但我确信,要定义常量,只需要使用#define
指令,后跟符号和要分配给它的值(即使值本身是一个表达式,即使这样的表达式引用了另一个常量),大括号和尾部分号就太多了:
// [...]
#define UNLEADED 3.45
#define SUPER (UNLEADED + 0.10)
#define PREMIUM (SUPER + 0.10)
//[...]
它在第一次尝试时就进行了这样的更正。
错误的原因是#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
变量不是指针类型。如果gallon被声明为指针类型,即double cost, *gallons;
,而cin
不在那里,那么代码会编译,但不会执行您期望的操作,可能会抛出segfault。
用#define定义的宏可能非常强大,也非常危险。在c++中通常有更好的方法来实现目标。在这种情况下,UNLEADED
、SUPER_UNLEADED
和PREMIUM
可以声明为const double
类型,即
const double unleaded = 3.45;
const double super = unleaded + 0.10;
const double premium = super + 0.10;
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++ 标记之前预期主表达式'('错误
- 正则表达式中带有卷轴大括号的正则表达式错误
- C++初学者错误:主要表达式错误
- 代数树表达式C++错误:未解析的外部符号"Public:_thiscall AlgebraicTreeExpression::~AlgebraicTreeExpression(void) ..."
- 使用多线程处理对象数组 - 无效使用 void 表达式错误
- 为什么 if constexpr 不会使这个核心常量表达式错误消失?
- 提升正则表达式错误:未初始化的提升::match_results
- C++比较表达式错误
- C++ "主表达式"错误
- C++ 正则表达式错误(未处理的异常)
- 'this'不能用于常量表达式错误 (C++)
- 代码块引发有关for_each的预期主表达式错误
- Boost Regex中的命名子表达式错误
- C++之前的主要表达式错误
- Ubuntu 上的正则表达式错误
- C++正则表达式错误
- 理解常量表达式错误
- 成员函数和预期的主表达式错误
- Xcode中应有表达式错误