类和结构体中的Static
类/结构体中的static,表明这个符号在这个类的所有对象共用。不属于任何一个对象。调用时直接用命名空间来访问这个符号。(函数内的静态变量不做讨论,和C语言是一样的)
下面是一些例子:
没有使用static:
#include <iostream>
using namespace std;
class Player{
public:
int x = 0, y = 0;
void move(int xa, int ya){
cout << "move from (" << x << "," << y << ") to \
(" << x+xa << "," << y+ya << ")" << endl;
x += xa;
y += ya;
};
};
int main()
{
Player player;
player.move(2,7);
player.move(3,5);
return 0;
}
静态成员变量:
#include <iostream>
using namespace std;
class Player{
public:
static int x, y;
void move(int xa, int ya){
cout << "move from (" << x << "," << y << ") to \
(" << x+xa << "," << y+ya << ")" << endl;
x += xa;
y += ya;
};
};
int Player::x;
int Player::y;
int main()
{
Player player1;
Player player2;
Player::x = 3;
Player::y = 6;
Player::y = 6;
player1.move(2,7);
player2.move(3,5);
return 0;
}
静态成员方法:
- 注意,类中静态方法不能访问非静态成员。
#include <iostream>
using namespace std;
class Player{
public:
int x = 0, y = 0;
static void move(Player& player, int xa, int ya){
cout << "move from (" << player.x << "," << player.y << ") to \
(" << player.x+xa << "," << player.y+ya << ")" << endl;
player.x += xa;
player.y += ya;
};
};
int main()
{
Player player;
Player::move(player, 2, 7);
Player::move(player, 3, 5);
return 0;
}