今天我正在學習和測試在C++中使用switch語句的不同形式;然後我寫了這段代碼,使一個功能,允許用戶輸入三個字符,其中兩個是案件和一個是比較字符(主要輸入)。 我決定使用指針,因爲我不能使用變量的情況下,但我的方法沒有工作,我只是不明白爲什麼?因爲使用指針實際上意味着我指向已經定義的地址的值!開關函數和指針(請參閱代碼)
這是錯誤的:
[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;
}
推測「沒有工作」意味着編譯器告訴你有什麼錯誤。仔細閱讀錯誤信息。如果你無法弄清楚它的含義,把它包含在你的問題中。 –
也與我們分享你在哪裏學習***「切換課程」***請! –
對不起,我的壞。所以你有什麼要說的呢? @ΦXocę웃Пepeúpaツ –