2017-07-13 19 views
-5

今天我正在學習和測試在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; 
} 
+4

推測「沒有工作」意味着編譯器告訴你有什麼錯誤。仔細閱讀錯誤信息。如果你無法弄清楚它的含義,把它包含在你的問題中。 –

+2

也與我們分享你在哪裏學習***「切換課程」***請! –

+0

對不起,我的壞。所以你有什麼要說的呢? @ΦXocę웃Пepeúpaツ –

回答

1

case *iloc:是不可能的。 case只接受編譯時已知的常量。在這種情況下使用if/else if而不是

+0

謝謝先生,但我可以說,使用指針使變量恆定,因爲它實際上指向到switch語句排隊之前定義的值(當它被定義時,它是一個常量!)? @IlBeldus –

+1

@NotGreen不是。你需要問自己的是:「當我編譯我的程序時,編譯器能夠知道'* iloc'的值嗎?如果答案是否定的,那麼它不能處於「案例」狀態。有關技術說明,請參閱https://stackoverflow.com/a/10965360/4124855 – IlBeldus

+0

@NotGreen不僅case不適用於字符串,但會發現您的iloc不是'const',這意味着它可以更改。如果它可以改變,那麼它在編譯時不是一個常量。 – UKMonkey