--University homework--返回泛型函數對象的引用(與指針或非指針屬性)
我已經與通用功能看起來像這樣的工作:
template<class T1, class T2, int max>
class Collection{
T1* _elements1[max];
T2* _elements2[max];
int _count;
public:
// ctor
bool AddElement(const T1& e1, const T2& e2)
{
for (int i = 0; i < _count; i++)
if (_elements1[i] == e1 && _elements2[i] == e2)
return false;
_elements1[_count] = e1;
_elements2[_count] = e2;
_count++;
return true;
}
int GetMax()const { return max;}
T1& GetElement1(int index)const { return *_elements1[index]; }
T2& GetElement2(int index)const { return *_elements2[index]; }
}
在main()
:
Collection<int, double, 6> collection;
for (int i = 0; i < 6; i++)
collection.AddElement(i, i + 0.4);
cout << collection << endl;
我也用const
在operator<<
這個類,一切的偉大工程,與0123沒有編譯器的投訴。
但是,今天我嘗試了這個班的稍微不同的版本,我們應該練習,因爲它會以某種形式在考試中。
template<class T1, class T2, int max>
class Collection{
T1 _elements1[max];
T2 _elements2[max];
int _count;
public:
// ctor
int GetMax()const { return max;}
T1& GetElement1(int index)const { return _elements1[index]; }
T2& GetElement2(int index)const { return _elements2[index]; }
}
的此不同的是,T1
和T2
不是的pointers
數組,但純對象數組,並在底部,當return
ING,有沒有必要取消引用。雖然我做google一下,發現如果我把另一個const
在這些功能中的前像這樣
error C2440: 'return' : cannot convert from 'const int' to 'int &'
:
const T1& GetElement1(int index)const { return _elements1[index]; }
const T2& GetElement2(int index)const { return _elements2[index]; }
然而,在後者的例子中,我得到這個錯誤
錯誤消失。
當然,這解決了我的問題,但我寧願瞭解爲什麼會發生這種情況以及發生了什麼。如果有一個簡單的方法可以解釋我提供的兩個示例之間的差異,那麼將不勝感激。
是什麼例子中的'T1'和'T2'無法編譯? – NathanOliver
在這個階段,我分別用'int'和'double'測試了一個簡單的for循環,調用集合函數AddElement(const T1&e1,const T2&e2)。請注意,在另一個示例(其中T1和T2是指針數組)中應用了相同的測試,並且它不會失敗。 – developer10
所以你同時調用'GetElement1'和'GetElement2',但只有'GetElement1'出錯? – NathanOliver