[英]error C4716: must return a value, thrown by function that actually does return a value
我的問題很簡單,但我不了解其原因,即使經過大量研究,也沒有類似的帖子出現,所以這里是:
我有以下運算符重載:
template <class T, size_t size>
inline Vector<T, size> operator + (Vector<T, size> &a, Vector<T, size> &b) {
Vector<T, size> result;
for (auto i = 0; i < size; ++i) {
result[i] = a[i] + b[i];
}
return result;
}
令人討厭的是,只有一個代碼路徑,並且該路徑還返回一個值,但是在Visual Studio 2013下編譯時,出現錯誤C4716,指出由編譯器實例化的函數“必須返回一個值”。 對於到目前為止我嘗試過的所有實例化,我都會收到此錯誤。 對於同一標頭中的所有其他運算符重載,我也都會收到此錯誤,所有這些標頭的結構都與上面的代碼段相似。 我在這里錯過明顯的東西嗎?
編輯:這是模板化的矢量類定義:
template <class T, size_t size>
struct Vector {
explicit Vector(T value = static_cast<T>(0)) {
for (auto i = 0; i < size; ++i) {
_data[i] = value;
}
}
explicit Vector(const Vector &other) {
for (auto i = 0; i < size; ++i) {
_data[i] = other._data[i];
}
}
explicit Vector(T values[size]) {
for (auto i = 0; i < size; ++i) {
_data[i] = values[i];
}
}
T & operator = (const Vector &other) {
for (auto i = 0; i < size; ++i) {
_data[i] = other._data[i];
}
return *this;
}
T & operator [] (size_t index) {
return _data[index];
}
T _data[size];
};
通過使Vector的副本構造函數非顯式,為我解決了該問題。
為了描述我如何得出這個結論,我專門研究了Vector的運算符功能:
template <>
inline Vector<int, 1> operator + (Vector<int, 1> &a, Vector<int, 1> &b) {
Vector<int, 1> result;
return result;
}
Visual Studio出現一個錯誤,指出不存在適合返回值的副本構造函數,此錯誤可以通過從副本構造函數中刪除顯式關鍵字來解決。 如果我正確理解了顯式副本構造函數的工作原理,這對我來說是顯而易見的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.