开关函数和指针(见代码)
Switch function and pointers(See the code)
今天我正在学习和测试在C++中使用switch语句的不同形式;然后我编写了这段代码来创建一个函数,允许用户输入三个字符,其中两个是大小写,一个是比较字符(Main input(。我决定使用指针,因为我不能为案例使用变量,但我的方法不起作用,我只是不明白为什么?因为使用指针实际上意味着我指向已经定义的地址的值!
这是错误:
[Error] 'iloc' cannot appear in a constant-expression
[Error] '*' cannot appear in a constant-expression
这是代码:
#include <iostream>
using std::cout;
using std::cin;
void switch_function(char i, char j, char c){
//inputing values by the user
cout <<"Insert i(char): ";
cin >> i;
cout <<"Insert j(char): ";
cin >> j;
cout <<"Insert c(char) "<< i <<" Or "<< j <<": ";
cin >> c;
//declaring pointers
char * iloc;
char * jloc;
char * cloc;
//registering memory adresses
iloc = &i;
jloc = &j;
cloc = &c;
//switch function
switch(*cloc){
case *iloc:
cout << i;
break;
case *jloc:
cout << j;
break;
}
}
int main(){
//s and f characters are the cases and the third f is the main user input.
switch_function('s', 'f', 'f');
cout <<"n";
int location;
int * target;
target = &location;
cout << &location;
cout <<"n"<< target + 1;
}
case *iloc:
是不可能的。case
只接受编译时已知的常量。在这种情况下使用if
/else if
相关文章:
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何防止C++遗留代码中的挂起指针
- 理解这行C++指针代码
- 为什么我们不在下面给出的代码中使用指针来实例化C++的实体对象?
- 为什么我的代码在指针方面停止运行?
- 以下与指针相关的代码的输出是什么?
- C++指针问题:如何修复这些代码中的错误?
- 如何使用指针直接从托管代码中的非托管代码中读取矢量数据
- 为什么下面的代码段返回指针指向的值而不是指针的地址?
- 使用指针向量(带代码)C++(以及对其使用的便利性的怀疑)时出现问题
- 为什么从 constexpr 引用生成的程序集代码与从 constexpr 指针生成的程序集代码不同?
- 由于指针算法错误,代码在 memcpy 中崩溃
- 为什么通过定义另一个指针单元格,整个代码停止工作?
- 使用指针编译代码后,.cpp文件将变为随机字符
- OpenCV如何处理Mat作为指针来加速代码
- 更正代码c++指针并删除
- C++指向对象的指针堆数组中,如何将字符串传递给特定对象?有一些代码请看一下:
- C++ 被此代码与多态性、指针和对象切片混淆
- LLvm Jit:如何从抖动代码中取消引用运行时指针?
- 将 C 代码移植到C++,将 void* 从 malloc 转换为所需指针的问题