2010-08-10 89 views
0

如何在不改變int數據狀態的情況下編譯下面的代碼?朋友和模板類

template<typename U> 
void Test(U); 

template< class T > 
class B { 
    int data; 
    public: 
    friend void Test<>(T); 
}; 

template<typename U> 
void Test(U u) { 
    B < int> b1; 
    b1.data = 7; 
} 

int main(int argc, char *argv[]) 
{ 
    char i; 
    Test(i); 
    system("PAUSE");  
    return 0; 
} 

上面的代碼導致編譯器錯誤,因爲b1.data是在TestU = char私人。

+0

目前沒有輸出。預期的行爲是什麼?怎麼了? – 2010-08-10 12:07:29

+1

@aman:你認爲你在寫'friend void Test <>(T);'? – 2010-08-10 12:10:36

+0

尼爾,你可以讓我知道爲什麼被標記爲國防部的關注? – 2010-08-10 12:11:38

回答

0

這使用VS2008進行編譯。不知道它是否符合標準。

#include <cstdlib> 

template<typename U> void Test(U); 

template< class T > class B { 
    int data; 
    public: 
    template <typename U > friend void Test(U); 
}; 

template<typename U> 
void Test(U u){ 
    B < int> b1; 
    b1.data = 7; 
    } 
int main(int argc, char *argv[]) 
{ 
    char i; 
    Test(i); 
    system("PAUSE");  
    return 0; 
} 
1

的問題是,你結交Test<U>B<U>(同一U),但是你想從Test<char>(不同U)訪問B<int>的內部。

這可能是最簡單的做任何B的任何測試朋友。