static 變數的用法

      在〈static 變數的用法〉中尚無留言

static 變數的使用方法相當奇特, 請看如下程式碼

#include 
using namespace std;
class Camera{
	public:
		static bool sound;
		void *playSound; //PlaySound類別置於底下, 所以無法宣告為PlaySound型態 
		Camera();
		void setSound(bool);
		void takePicture();
};
class PlaySound{
	public:
		void play();
};
bool Camera::sound=true;
void Camera::setSound(bool f){
	sound=f;
}
Camera::Camera(){
	playSound=new PlaySound();
}
void Camera::takePicture(){
	printf("Start take picture\n");
	((PlaySound*)playSound)->play(); //將void* 轉換成PlaySound* 
}
void PlaySound::play(){
	if(Camera::sound)
		printf("play sound\n");
	else
		printf("no sound\n");
		
}
int main(){
	Camera *camera=new Camera();
	camera->setSound(true);
	camera->takePicture();
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *