我有一個類似的代碼:
template <typename T>
struct B
{
B &operator =(const T &) { return *this; }
};
struct D : B<int> {};
int main()
{
D d;
d = 0;
return 0;
}
失敗了:
error: no viable overloaded '='
d = 0;
~ ^ ~
note: candidate function (the implicit copy assignment operator) not viable: no known conversion from 'int' to 'const D' for 1st argument
struct D : B<int> {};
^
note: candidate function (the implicit move assignment operator) not viable: no known conversion from 'int' to 'D' for 1st argument
struct D : B<int> {};
^
這個錯誤很容易發現和理解:D缺少帶有 的賦值運算子int,即使它的基類有它。從c 11之后,我們可以解決這個問題,將賦值運算子從基礎物件“提升”到派生物件:
struct D : B<int> { using B::operator =; /* Easy fix! */ };
但我正在做一個C 98專案,因此此修復程式不可用。在 C 11 之前這是如何解決的?
uj5u.com熱心網友回復:
using繼承基類方法的宣告已經在 C 98 中作業。
它是using繼承建構式的宣告,而不是。
template <typename T>
struct B {
B(const T&) {}
B &operator=(const T&) { return *this; }
};
struct D : B<int> {
// using B<int>::B; // error, constructors can't be inherited
using B<int>::operator=;
};
然后您需要實作一個初始化基類的方法:
struct D : B<int> {
D(int v) : B(v) {} // this works
using B<int>::operator=; // and this too
};
uj5u.com熱心網友回復:
首先,該程式(帶有using 宣告)適用于 C 98。使用 C 98 的作業演示。
也就是說,C 98 允許在派生類中對基類的賦值運算子使用 using 宣告。以下是標準中的相關文本:
如果從基類引入派生類作用域的賦值運算子具有派生類的復制賦值運算子的簽名(12.8),則使用宣告本身不會抑制派生類復制賦值的隱式宣告操作員; 基類的復制賦值運算子被派生類的隱式宣告的復制賦值運算子隱藏或覆寫,如下所述。
(強調我的)
再次注意,重要的是允許基類賦值運算子的 using 宣告。
現在,您可以為顯式使用基類的派生類定義賦值operator=,如下所示:
struct D : B<int> {
D& operator=(const int& obj) {
B<int>::operator=(obj); //use base class assignment operator
return *this;
}
};
uj5u.com熱心網友回復:
但是我正在開發一個 c 98 專案,所以這個修復程式不可用。在 C 11 之前這是如何解決的?
定義一個operator=呼叫:DB::operator=
struct D : B<int> {
D& operator=(const int &rhs) {
B<int>::operator=(rhs);
return *this;
}
};
uj5u.com熱心網友回復:
您可以將所需的運算子函式添加到派生類中,并從中呼叫相應的基類運算子:
template <typename T>
struct B {
B& operator = (const T&) { return *this; }
};
struct D : B<int> {
D& operator = (const int& rhs) {
B<int>::operator = (rhs);
return *this;
}
};
int main()
{
D d;
d = 0;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496815.html
