如果我想在每次创建新机器人时更新我的静态 id 以id+=1
,我该怎么做,在哪里?我试过这个,但它仍然不起作用
class Robot{
Robot(){
static int id_count=0;
id=id_count++;
}
int id;
int x;
int y;
}
一种方法可能是将其放置在构造函数中。
class Robot{
public:
Robot() {
static int id_count=0;
id = id_count++;
}
int id;
int x;
int y;
}
你可以在构造函数中执行此操作:
class Robot {
static int id;
Robot() { ++id; }
int x;
int y;
};
如果您希望每个机器人都有自己的 id,那么:
class Robot {
static int refcount;
int id;
int x;
int y;
public:
Robot() {
id = ++refcount;
}
}
创建一个static
变量(不是id
(,初始化它,并在构造函数中递增并分配给id
。
工作和最简化的代码。
class Robot
{
static int count;
int id, x, y;
public:
Robot()
{
id = count++;
}
};
int Robot::count = 0;
完整的工作计划:
#include<iostream>
class Robot
{
static int count;
int id, x, y;
public:
void show(){std::cout << id << std::endl;}
Robot(){id = count++;}
};
int Robot::count = 0;
int main()
{
Robot a, b, c;
a.show();
b.show();
c.show();
return 0;
}
你可以在这里运行
你需要在类中有一个静态的 int id,这样当创建Robot
的另一个实例时,它也可以访问它。
#include <iostream>
using namespace std;
class Robot {
public:
static int id;
int x, y;
// Give the class a constructor. This is called whenever a new instance of
// Robot is created.
Robot(int x, int y) {
this -> x = x;
this -> y = y;
++id;
cout << "I am a new robot." << endl;
cout << "My x value is " << x << endl;
cout << "My y value is " << y << endl;
cout << "My id is " << id << endl;
}
};
int Robot::id = 0;
int main(int argc, char *argv[]) {
// Create 5 new instances of robots and
// say how many robots have been created.
for(int i=0; i<5; ++i) {
Robot r = Robot(1 * i, 1 * (i * 2));
cout << "There are now " << r.id << " robots" << endl;
cout << endl;
}
return 0;
}
输出:
I am a new robot.
My x value is 0
My y value is 0
My id is 1
There are now 1 robots
I am a new robot.
My x value is 1
My y value is 2
My id is 2
There are now 2 robots
I am a new robot.
My x value is 2
My y value is 4
My id is 3
There are now 3 robots
I am a new robot.
My x value is 3
My y value is 6
My id is 4
There are now 4 robots
I am a new robot.
My x value is 4
My y value is 8
My id is 5
There are now 5 robots