试图避免使用C风格的结构并制作我的第一个c ++类。但问题是......
好的,所以使用OpenCv我定义了一个最小的类来显示我遇到的问题。 MatrixMathTest.cpp:
#include "MatrixMathTest.h"
MatrixMathTest::MatrixMathTest(){
float temp_A[] = {1.0, 1.0, 0.0, 1.0};
Mat A = Mat(2,2, CV_32F , temp_A);
float temp_x[] = {3.0, 2.0};
Mat x = Mat(2,1, CV_32F , temp_x);
}
void MatrixMathTest::doSomeMatrixCalcs(){
x = A * x; //expecting matrix mults, not element wise mults
A = A.inv(); //proper matrix inversion
}
然后是MatrixMathTest.h:
#include "opencv2/opencv.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
class MatrixMathTest {
public:
MatrixMathTest();
void MatrixMathTest::doSomeMatrixCalcs();
private:
Mat x;
Mat A;
};
然后运行:
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include "MatrixMathTest.h"
using namespace cv;
using namespace std;
void main(int argc, char** argv) {
float temp_A[] = {1.0, 1.0, 0.0, 1.0};
Mat A = Mat(2,2, CV_32F , temp_A);
A = A.inv();
cout << A << endl;
float temp_x[] = {3, 2};
Mat x = Mat(2,1, CV_32F , temp_x);
x = A * x;
cout << x << endl;
MatrixMathTest tester;
tester.doSomeMatrixCalcs();
}
main中的相同代码将按预期工作,但一旦它在类中失败:
如果我放置A.inv();第一行我略有不同:
当我使用CV_32F作为类型直接在main中运行相同的代码时,没有断言失败。搜索该错误消息shows people solving it by changing the variable types但我已经尝试了断言所提及的所有不同数字变量类型等等,它只是留在CV_32F,因为这是我尝试的最后一次。
我认为这与在课堂上有关? ??
但是什么?或其他什么? 某事(非常基本?)我还没学习?...如果它与类型有关,如何协调想要最终在同一矩阵上同时进行多元化和反转 - 这些断言中的不同类型是否排除了???
答案 0 :(得分:2)
您正在屏蔽A
中的类变量x
和MatrixMathTest::MatrixMathTest()
。
由于您将它们声明为Mat A = ...
,因此您正在初始化这些临时对象,而不是您的类的成员对象。
也就是说,当您运行doSomeMatrixCalcs()
时,您正在使用成员对象this.A
和this.x
,但它们从未被初始化。因此它们包含错误数据,操作失败。
将Mat A = ...
替换为A = ...
或this.A = ...
,事情应该会更好。
答案 1 :(得分:1)
您的类构造函数已隐藏成员变量,请尝试执行此操作:
MatrixMathTest::MatrixMathTest(){
float temp_A[] = {1.0, 1.0, 0.0, 1.0};
A = Mat(2,2, CV_32F , temp_A);
float temp_x[] = {3.0, 2.0};
x = Mat(2,1, CV_32F , temp_x);
}
请注意,我已从Mat
和A
声明中删除了x
。所以之前您创建的局部变量与您的类成员变量具有相同的名称。然后,当你来调用doSomeMatrixCalcs
时,它使用的成员变量是未初始化的,因此是断言。