C++中的静态对象

Jac*_*Box -1 c++ object

我有Mtx在矩阵之间做一些计算

Mtx M1(rows1,cols1,1); //instantiate data members and fill the matrix with 1s
Mtx M2(rows2,cols2,2); //instantiate data members and fill the matrix with 2s

Mtx M3(rows3,cols3,0); //instantiate data members and fill the matrix with 0s


M3 += M1; //+= is overloaded - First M3
M3 -= M2; //-= is overloaded - Second M3
Run Code Online (Sandbox Code Playgroud)

首先M3需要M3的是用零填充,并将其添加到M1和答案将被分配给M3.我这里没问题.

问题出在第二个M3!它不会减去M3用零填充的内容,而是使用前一个操作的结果并从中减去M2.

如何制作M3保持其价值的静态?它是否与静态对象有关?我希望你明白我的意思!

感谢您的帮助......

Aes*_*ete 5

这是因为您正在使用+=运营商.您正在为左侧的对象分配 新值.

使用时,+=您正在更改M3的值.

你想要的是这个:

Mtx M4 = M3 + M1;
Mtx M5 = M3 - M2;
Run Code Online (Sandbox Code Playgroud)

甚至更好:

const static Mtx ZERO_MTX(rows3,cols3,0);
Mtx M4 = ZERO_MTX + M1;
Mtx M5 = ZERO_MTX - M2;
Run Code Online (Sandbox Code Playgroud)