我们可以将引用绑定到函数的返回值吗
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
引用。但是CCD_ 10返回一个CCD_。
写入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;
}
}
}
相关文章:
- 程序不向函数返回值
- 如何将不可移动和不可复制的函数返回值获取到数组中
- 存储函数返回值或立即使用c++
- 如何删除新分配的字符,这也是函数返回值?
- 不从函数返回值会导致段错误
- lambda 函数返回值的有效性
- 如何获取有关 Visual Studio 代码分析中未经检查的函数返回值的警告
- 存储指向函数返回值的指针
- 在 OOP 中,调用函数返回值还是直接调用值更快?
- 函数返回值的自动类型扣除
- 为循环中多次调用的函数返回值预分配内存的正确方法是什么
- 函数返回值的位运算符提升
- 从捕获 constexpr 函数返回值的变量中删除 constexpr 会删除编译时计算
- C++ ReSharper - 生成函数返回值/参数类型的变量
- std::clamp - 检测函数返回值是否绑定到 const T&
- C 递归函数返回值
- 是否可以在C 中使回调函数返回值
- C++标准是否保证函数返回值具有常量地址?
- 将函数返回值传递给引用参数会导致 GCC 中的编译错误
- 函数返回值错误