[英]Can we bind a reference to a return value of a function?
這是我的問題:
我有兩個類Vector
和Matrix
,並且定義了兩個函數,一個函數用於計算向量與矩陣的乘法,另一個函數是將值分配給新向量。
這是代碼:
file: Matrix.cpp
Vector Matrix::operator*(const Vector& v)const {
assert(v.length == numRows);
Vector temp(v.length);
for (int j = 0; j < numCols; j++)
for (int k = 0; k < v.length; k++)
temp.contents[j] += v.contents[k] * contents[k][j];
return temp;
};
file: Vector.cpp
Vector& Vector::operator=(Vector& v){
assert(v.length == length);
if (&v != this) {
for (int i = 0; i < length; i++)
setComponent(i, v.contents[i]);
}
return *this;
};
假設我已經很好地定義了4 * 4矩陣m1
和1 * 4向量v1
這是我的main()
函數代碼的一部分,
file: main.app
Vector v2(4);
v2 = m1 * v1;
它可以編譯,但是會遇到問題。
誰能給我一個如何處理的提示? 是否因為我試圖將引用與函數的返回值綁定? 非常感謝!
在您的代碼中,您定義了賦值運算符,例如Vector& Vector::operator=(Vector &v)
。 但這應該類似於Vector& Vector::operator=(Vector const & v)
。 原因是Vector &v
引用lvalue
引用。 但是m1 * v1
返回一個rvalue
。
寫入地址0x00 .... 04比空ptr偏移4個字節。 這意味着您正在嘗試通過未初始化的指針進行寫入。 如果使用調試器,則可以找到嘗試執行此操作的確切代碼。
注意不要與std :: vector發生名稱沖突。 假設您有構造函數,請復制構造函數(在下面給出,還需要賦值運算符),以正確分配並將所有元素初始化為零
Vector::Vector(int sz) {
contents = new int[length = sz]; // allocation
for (int i = 0; i < sz; i++) {
contents[i] = 0;
}
}
Vector::Vector(const Vector& v) {
contents = new int[length = v.length]; // allocation
for (int i = 0; i < length; i++) {
contents[i] = v.contents[i];
}
}
Matrix::Matrix(int rows, int cols) {
contents = new int *[numRows = rows]; // allocation
for (int i = 0; i < rows; i++) {
contents[i] = new int[numCols = cols]; // allocation
for (int j = 0; j < cols; j++) {
contents[i][j] = 0;
}
}
}
Matrix::Matrix(const Matrix& m) {
contents = new int *[numRows = m.numRows]; // allocation
for (int i = 0; i < numRows; i++) {
contents[i] = new int[numCols = m.numCols]; // allocation
for (int j = 0; j < numCols; j++) {
contents[i][j] = 0;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.