如果我想在每次创建新Robot时将静态ID更新为id+=1
,
我怎么能这样做,在哪里?
我试试这个,但它仍然无法正常工作
class Robot{
Robot(){
static int id_count=0;
id=id_count++;
}
int id;
int x;
int y;
}
答案 0 :(得分:2)
一种方法是将它放在构造函数中。
class Robot{
public:
Robot() {
static int id_count=0;
id = id_count++;
}
int id;
int x;
int y;
}
答案 1 :(得分:1)
您可以在构造函数中执行此操作:
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;
}
}
答案 2 :(得分:0)
制作一个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;
}
您可以运行here
答案 3 :(得分: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