有下面语句
void testswitch(){
CString test="hello";
switch(test){
case "hello":
AfxMessageBox("yes");
break;
default:
break;
}
}
编译无法通过.编译错误信息
error C2450: switch expression of type 'class CString' is illegal
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
error C2051: case expression not constant
warning C4065: switch statement contains 'default' but no 'case' labels
从语法上分析,这有什么错误?最后一句警告,代码中明明有case和default,为什么还警告说没有?
void testswitch(){
CString test="hello";
switch(test){
case "hello":
AfxMessageBox("yes");
break;
default:
break;
}
}
编译无法通过.编译错误信息
error C2450: switch expression of type 'class CString' is illegal
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
error C2051: case expression not constant
warning C4065: switch statement contains 'default' but no 'case' labels
从语法上分析,这有什么错误?最后一句警告,代码中明明有case和default,为什么还警告说没有?
解决方案 »
- 在98系统里面,怎么样能监控到系统生成了文件,修改了文件呢?
- 有关用Windows API 函数进行SCSI接口的磁带机编程的问题
- 谁有BCGControlBar Professional Edition v6.74安装序列号?
- 简单template问题
- 为什么不能加载"Psapi.dll",求助
- 请教:如何保证“发送 N 个数据包,收到的也是 N 个数据包”-关于数据包合并的问题,100分相赠。
- 有关动态生成控件并显示的问题
- 请问如何将我的表格内容以Excel格式保存成.xls文件?
- mfc中 cimage 用draw画图 显示不出来
- 如何调用ODBC注册的对话框?
- CFormView加入背景图片,当FormView大小改变时,为什么原来的位图不擦除
- 100分求一个多线程管理类的实现方法!求各位大哥大姐们知道的给点提示方法?
switch只能接受整型
你这里面直接用CString作为分支,肯定不行。
switch expression of type 'type' is illegalThe specified switch expression evaluated to an illegal type.A switch expression must evaluate to an integral type or a class type that has an unambiguous conversion to an integral type.If the expression evaluates to a user-defined type, a conversion operator needs to be supplied.The following is an example of this error:class X
{
public:
int i;
} x;
class Y
{
public:
int i;
operator int() { return i; } // conversion operator
} y;
void main()
{
int j = 1;
switch ( x ) // error, x is not type int
{
default: ;
}
switch ( y ) // OK
{
default: ;
}
}
大概意思是 SWITCH 要用整形。
1.zaodt在msdn中找到错误的代码解释,这是怎样找到的?
2.zaodt的那个例子switch(x)是错误的,而switch(y)则是正确的.这个例子不是看得很明白,谁可以解释一下?
谢谢了.
你可以改成case "h":
或者自己define hello 的对应串
1、你在MSDN中输入错误编号C2450就可以看到了
2、因为Y类中有进行operator int() { return i; } // conversion operator,返回的类型符合switch语句的要求。
{
public:
int i;
operator int() { return i; } // conversion operator
} y;
整型数应该是调用了一个方法之后返回的.但是switch(y)中的y是一个Y类的对象,怎么变成一个返回的整型数了?如果是switch(y.int())倒不难理解了,因为这个方法返回了一个整型数i,但是switch(y)这个表达式实在有点搞不懂.是不是这个表达式中的y在什么时候调用了那个返回i的方法?麻烦解释一下.
还有几个问题:
1.operator int() { return i; }是什么意思?
2.这个方法在什么时候会被调用?
3.operator为什么作为一个返回值类型来使用?
4.int是一个关键词,为什么可以作为函数标识符?
是C++运算符重载里的内容,叫做:类类型转换函数。
其功能是将类Y的对象转换为类型为int的数据。
在执行switch(y)语句时,调用该函数。
另外想问个问题,是不是c++里的所有默认操作都可以用operator xx改写?
不能放在SWITCH里面,拷贝出去就好了
{
public:
int i;
operator int() { return i; } // conversion operator
} y;
一个问题:switch(y)的时候会发生强制转换,但y原来的类型又是什么呢?更加通用一点的问法就是:类默认的返回类型是什么?