我希望+ =和<<将相同,但是<<不起作用。
这是我的代码:
#include <iostream>
using namespace std;
struct Pos{
int x;
int y;
void operator+=(Pos vel){
x += vel.x;
y += vel.y;
}
};
struct Obj{
string name;
Pos pos;
void info(){
cout << name << endl;
cout << pos.x << ", " << pos.y << endl;
cout << endl;
}
void operator<<(Pos vel){
pos += vel;
}
void operator+=(Pos vel){
pos += vel;
}
};
int main(){
Pos p{10, 20};
Obj car{"Car", p};
Obj truck{"Big truck", {40, 20}}; …Run Code Online (Sandbox Code Playgroud) 我创建了一个包含对象的2D数组,每个对象都有两个变量。
当我打印出这些对象时,我发现每个对象都具有相同的值。
如果更改其中一个对象,其他对象也将更改。
class test{
constructor(x, y){
self.x = x;
self.y = y;
}
print(){
console.log(self.x, self.y);
}
}
arr = new Array(3);
for(let i=0;i<3;i++){
arr[i] = new Array(3);
}
for(let i=0;i<3;i++){
for(let j=0;j<3;j++){
arr[i][j] = new test(i, j);
}
}
for(let i=0;i<3;i++){
for(let j=0;j<3;j++){
arr[i][j].print();
}
}Run Code Online (Sandbox Code Playgroud)
它只打印9 22。我不知道发生了什么。
即使我尝试过:
arr[1][2] = new test(2, 3);
Run Code Online (Sandbox Code Playgroud)
打印9 2 3。
如果有人帮助我,我将不胜感激。
:P