我正在为C ++中的double分配一个指针。当我取出指针时,它运行良好,但是当我使用指针运行它时,我收到一条错误消息:“无法在分配中将'double *'转换为'double'”。我不知道为什么这会给我这个错误。任何帮助是极大的赞赏。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double ROP, HW, OT,oSal;
int choice;
char choice2= (toupper(choice2));
double * pbsal[2];
double bsal[2];
cout<<setprecision (2)<<fixed;
cout<<"Welcome to the salary calculator!!!"<< endl;
cout<<""<<endl;
cout<<"Please enter your hourly rate: "<<endl;
cin>>ROP;
while(choice != 3){
cout<<"Would you like to:"<<endl;
cout<<"1. Enter the number of hours you worked?"<<endl;
cout<<"2. Enter the number of overtime hours you worked?"<<endl;
cout<<"3. Exit the program"<< endl;
cin>>choice;
switch(choice){
case 1:
cout<<"Please enter the number of hours you worked(excluding
overtime):"<<endl;
cin>>HW;
cout<<"Would you like to see your salary based on the number of
hours you worked?"<<endl;
cin>> choice2;
break;
case 2:
cout<<"Please enter the number of hours of overtime you worked:"<<
endl;
cin>>OT;
oSal = (ROP*1.5)*OT;
cout<<"Your overtime salary is: $"<<oSal<<endl;
break;
}
switch(choice2){
case 'Y':
for(int i =0; i<=2; i++){
bsal[i]=ROP*HW;
*pbsal[i]= &bsal[i];
}
cout<<"Your salary based on the hours you provided is: $"
<<bsal<<endl;
cout<<"test"<<*pbsal[0]<<endl;
cout<<""<<endl;
break;
case 'N':
cout<<"Thank you!"<<endl;
cout<<""<<endl;
break;
}
}
}
这是我收到的错误:
15:45:42 **** Incremental Build of configuration Debug for project Module4 ****
make all
Building file: ../src/Module4.cpp
Invoking: Cygwin C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Module4.d" -MT"src/Module4.o" -o "src/Module4.o" "../src/Module4.cpp"
../src/Module4.cpp: In function 'int main()':
../src/Module4.cpp:64:25: error: cannot convert 'double*' to 'double' in assignment
*pbsal[i]= &bsal[i];
^
make: *** [src/subdir.mk:20: src/Module4.o] Error 1
"make all" terminated with exit code 2. Build might be incomplete.
我希望能够将指针分配为双精度型。
答案 0 :(得分:2)
C ++中的指针与C指针略有不同。
应该使用关键字new
调用它,以进行有效的内存管理。
double *pbsal = new double[2];
现在pbsal[0]
和pbsal[1]
只是双精度值。循环应该是i<2
而不是i<=2
。
bsal[i] = ROP*HW;
pbsal[i] = bsal[i];