2016-08-07 33 views
-3

編譯器說,A和B是不是在範圍中聲明:這個程序有什麼問題?說A和B不在範圍

#include <iostream> 

using namespace std; 

class sample { 
    private: 
     int a, b; 
    public: 
     void setvalue() { 
      a=25; b=40;`enter code here` 
     } 
    friend int sum(sample s1); //says a and b are not in the scope 
}; 

int sum(sample s1) { 
    return a+b; //says a and b are not in the scope 
} 

int main() { 
    sample x; 
    x.setvalue(); 
    cout<<"\nSum ="<<sum(x); 
    return 0; 
} 
+2

尋找過去可怕的編輯(請修復它)它看起來像你試圖訪問全局函數中的'a'和'b'('sum')。 *你想用誰的'a'和'b'?你需要一個'sample'的實例。你的意思是使用's1.a'等嗎? – Biffen

+3

預計多次降價,直到您修復代碼,這是目前廢話。 –

回答

1

變化:

return a+b; 

return s1.a+s1.b; 
+0

爲什麼不在課堂內定義和數? – martijnn2008

+0

因爲那麼它將不再是一個免費的功能,我想OP想要一個免費的功能。 – marcinj

0

變量ab是類sample的成員。這意味着這些變量必須爲使用.運營商的sample現有實例的一部分進行訪問:

return a + b; // Tries to find variables named 'a' and 'b', but fails (error) 
return s1.a + s1.b; // Uses the members of s1, finds them, and works correctly 

然而一類的成員函數中,就沒有必要使用「S1」 - 變量已經因爲它們與函數(類範圍)在同一範圍內。所以,你可以重寫類:

添加下面的類,在市民:

int sum() 
{ 
    return a + b; 
} 

,並在主:

cout << "\nSum" << x.sum(); 
+0

感謝兄弟:)謝謝兄弟:) –

+0

和我認爲sum(x)是正確的one..for x.sum()編譯器給出了錯誤 –

+0

@Nareshjungshahi我的意思是,如果你添加了我寫給這個類的函數,那麼'x.sum()'可以工作。順便說一句,請標記爲答案,如果它的工作。 – otah007

相關問題