我正在嘗試制作一個Matrix可以處理各種資料型別的結構,包括我的Complex結構:
struct Complex {
double re = 0, im = 0;
Complex operator*(const Complex& other) const {
return Complex(re * other.re - im * other.im, im * other.re re * other.im);
}
Complex operator*(const double& other) const {
return Complex(re * other, im * other);
}
Complex() {}
Complex(double a) : re(a) {}
Complex(double a, double b) : re(a), im(b) {}
};
std::ostream& operator<<(std::ostream& out, Complex z) {
out << z.re << " " << z.im << "i";
return out;
}
template <typename T>
Complex operator*(const T& c, const Complex& z) {
return z * c;
}
顯而易見的方法是在下面的代碼中制作一個模板:
template <typename T>
struct Matrix {
std::vector<T> m;
unsigned int rows, cols;
Matrix<Complex> operator*(const Complex& z) const {
Matrix<Complex> result(rows, cols);
for (int i = 0; i < m.size(); i ) {
result.m[i] = m[i] * z;
}
return result;
}
void operator*=(const Complex& z) {
(*this) = (*this) * z; // <- ideally we're trying to get this to work
}
void operator=(const Matrix<T>& other) {
rows = other.rows;
cols = other.cols;
m.resize(rows * cols);
m = other.m;
}
Matrix(const unsigned int& rows, const unsigned int& cols) : rows(rows), cols(cols) {
m.resize(rows * cols);
}
Matrix(const Matrix<T>& other) : rows(other.rows), cols(other.cols) {
(*this) = other;
}
};
int main() {
Complex z(1, 1);
Matrix<double> A(1, 1);
A.m[0] = 2.0;
std::cout << (A * z).m[0] << std::endl; // works as it should because a temporary Matrix<Complex> gets created
A *= z; // and here we're introducing the problem
std::cout << A.m[0] << std::endl;
}
呼叫操作員時會出現問題*=。我們試圖呼叫一個不存在的=運算子多載。我的第一次嘗試是寫這樣的東西:
template <typename T_other>
void operator=(const Matrix<T_other>& other) {
rows = other.rows;
cols = other.cols;
m.resize(rows * cols);
for (int i = 0; i < m.size(); i ) {
m[i] = other.m[i];
}
}
然而,這會導致其他問題:
- 的型別
A仍然是Matrix<double>,并且在乘法之后應該是Matrix<Complex>存盤復數。 - 沒有從
Complexto的轉換,double因為它會導致資料丟失(虛部)。
另外,我想避免為 創建模板專業化Matrix<Complex>,但如果沒有其他方法,我會接受它。
uj5u.com熱心網友回復:
C 是靜態型別的。 一旦宣告了變數和型別,就不能更改該變數的型別。
template <typename T>
struct Matrix {
void operator*=(const Complex& z) {
(*this) = (*this) * z;
}
}
您的*=運算子多載Matrix沒有意義。AComplex可以保存 adouble的虛部為 0 的值,但 adouble永遠不能保存 a 的值Complex。
將實數矩陣乘以復數必然產生復數矩陣。因此,您嘗試將復雜的 RHS 分配給真正的 LHS - 要么這沒有意義,不應該這樣做,要么您對如何轉換它有一些想法(例如,保留實部,保留絕對值等)然后有Matrix<double>從Matrix<Complex>. _
實數是復數的一個子集,所以如果你以后想要讓它變得復雜,就從頭開始做A。Matrix<Complex>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/473696.html
