我必须在我的新型符号上计算一个程序,我遇到了一个我无法解决的问题。
代码:
typedef struct{
Symbol a1, a2, w_wcz, w_ok;
char oper, rown;
int Oblicz(){
if(rown != '='){
cerr << "Blad, brak symbolu rownosci!" << endl;
return 0;}
switch(oper){
case '+':
w_ok=a1+a2;
case '-':
w_ok=a1-a2
case '*':
w_ok=a1*a2;
case '/':
w_ok=a1/a2;
default:
cerr << "Blad, nieznany operator!" << endl;
return 0;}
}
}WyrAlg;
a,b,c,d,e是枚举符号类型。 +, - ,*和/运算符因两个符号而重载并且工作正常,当我尝试将其放入方法时,它只会出现问题。
主要是我
WyrAlg Wyr;
[it is initialized here with values]
Wyr.Oblicz();
我得到的是:
[tjakubo2@diablo:~/kpo/lab04]$ make
g++ -pedantic -Wall -o dzialok.out dzialaniamod.cpp
dzialaniamod.cpp: In member function 'int<anonymous struct>::Oblicz()':
dzialaniamod.cpp:32:8: error: invalid conversion from 'int' to 'Symbol' [-fpermissive]
w_ok=a1+a2;
^
dzialaniamod.cpp:40:12: error: invalid conversion from 'int' to 'Symbol' [-fpermissive]
w_ok=a1-a2;
^
dzialaniamod.cpp:48:12: error: invalid conversion from 'int' to 'Symbol' [-fpermissive]
w_ok=a1*a2;
^
dzialaniamod.cpp:56:12: error: invalid conversion from 'int' to 'Symbol' [-fpermissive]
w_ok=a1/a2;
^
*** Error code 1
make: Fatal error: Command failed for target `dzialok.out'
我无法确定发生了什么,需要帮助。提前谢谢!
编辑: 包括重载运算符: (可能不清楚,但工作正常)
enum Symbol {e,a,b,c,d};
Symbol tab_dod[5][5]= {{e,a,b,c,d},{a,b,c,d,e},{b,c,d,e,a},{c,d,e,a,b},{d,e,a,b,c}};
Symbol operator + (Symbol x, Symbol y){
return tab_dod[x][y];
}
澄清编辑2: 函数版本工作正常,如果需要,请将其粘贴到此处: 唯一的区别是w_ok在WyrAlg之外,只是在功能上:
int ObliczWyr(WyrAlg Wyr){
Symbol w_ok;
if(Wyr.rown != '='){
cerr << "Blad, brak symbolu rownosci!" << endl;
return 0;}
switch(Wyr.oper){
case '+':
w_ok=Wyr.a1+Wyr.a2;
[stuff]
return 2;}
case '-':
w_ok=Wyr.a1-Wyr.a2;
[stuff]
return 2;}
case '*':
w_ok=Wyr.a1*Wyr.a2;
[stuff]
return 4;}
case '/':
w_ok=Wyr.a1/Wyr.a2;
[stuff]
return 4;}
default:
cerr << "Blad, nieznany operator!" << endl; // jesli nieznany operator
return 0;}
}
答案 0 :(得分:1)
此代码已成功编译
#include <iostream>
enum Symbol {e,a,b,c,d};
Symbol tab_dod[5][5]= {{e,a,b,c,d},{a,b,c,d,e},{b,c,d,e,a},{c,d,e,a,b},{d,e,a,b,c}};
Symbol operator + (Symbol x, Symbol y)
{
return tab_dod[x][y];
}
int main()
{
typedef struct
{
Symbol a1, a2, w_wcz, w_ok;
char oper, rown;
int Oblicz()
{
switch(oper)
{
case '+':
w_ok=a1+a2;
break;
default:
std::cerr << "Blad, nieznany operator!" << std::endl;
break;
}
return 0;
}
} WyrAlg;
WyrAlg alg;
alg.a1 = e;
alg.a2 = a;
alg.oper = '+';
alg.Oblicz();
}
也许您在结构定义之后声明了运算符。