2013-11-21 81 views
1

在執行這個計劃,我得到以下編譯錯誤:爲什麼友元函數不能訪問類的私有成員

template.cpp: In function ‘std::istream& operator>>(std::istream&, currency&)’: 
template.cpp:8: error: ‘int currency::doller’ is private 
template.cpp:25: error: within this context 
template.cpp:9: error: ‘int currency::cents’ is private 
template.cpp:25: error: within this context 

這是C++程序:

#include <iostream> 
using namespace std; 

class currency 
{ 
    private: 
     int doller; 
     int cents; 

    public: 
     currency():doller(0),cents(0) {} 
     friend ostream& operator<< (ostream& stream, const currency& c); 
     friend istream& operator>> (istream& in, const currency& c); 

     /*friend istream& operator>> (istream& in, const currency& c) 
     { 
      in >> c.doller >> c.cents; 
      return in; 
     } */ 
}; 

istream& operator>> (istream& in, currency& c) 
{ 
    in >> c.doller >> c.cents; 
    return in; 
} 

ostream& operator<< (ostream& stream, const currency& c) 
{ 
    stream << "(" << c.doller << ", " << c.cents << ")"; 
    return stream; 
} 

template <class T> 
void function(T data) 
{ 
    cout << "i am in generalized template function: " << data << endl; 
} 

template<> 
void function (int data) 
{ 
    cout << "This is: specialized for int" << data << endl; 
} 

int main() 
{ 
    currency c; 
    cin >> c; 
    function (c); 
    function (3.14); 
    function ('a'); 
    function (12); 
    return 0; 
} 

在同時的std :: ostream的&操作< <(STD :: ostream的&,常量貨幣&)不給任何錯誤。我想了解程序中是否有任何錯誤?

此外,雖然我給裏面的類的defition這是錯誤:

template.cpp: In function ‘std::istream& operator>>(std::istream&, const currency&)’: 
template.cpp:18: error: ambiguous overload for ‘operator>>’ in ‘in >> c->currency::doller’ 

回答

3

您的operator>>定義,這意味着你的聲明和定義不同的運營商的簽名錯誤。你需要從friend istream& operator聲明刪除const它是friend運營商的定義:

friend 
istream& operator>> (istream& in, currency& c) 
//         

模棱兩可的過載是出於同樣的原因。你有兩個匹配的功能。上述建議的解決方案將解決這兩個問題。

+0

根據它的邏輯運算符貨幣不應該是const,因爲他在這個語句中修改它>> c.doller >> c.cents;因此,最好是改變朋友的簽名(忽略常數) –

+0

@spin_eight當然,我已經改變了這一切。 – juanchopanza

+0

感謝您的快速響應。 –

1

operator>>的簽名不匹配的一個聲明爲類的朋友:

istream& operator>> (istream& in, currency& c);  // outside class 
istream& operator>> (istream& in, const currency& c); // friend class 
//        ^^^^^ 
0

你需要在方法聲明中刪除const簽名:

friend istream& operator>> (istream& in, currency& c); 

的函數,你定義沒有const在裏面,所以它不是你聲明爲friend的函數,因此不能訪問private成員。需要注意的是,宣佈currency對象const沒有意義或者,因爲你使用插播廣告經營者改變它。

相關問題