【发布时间】:2016-02-20 17:13:30
【问题描述】:
所以我用 C++ 编写了这段代码,这只是学习 C++ 的练习:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int random(int max){
srand(time(NULL));
return rand() % max;
}
class player{
public:
player(){
liv = 5;
mun = 3;
}
void Rename(char name[]){
name = name;
}
void set_group(player pl[]){
pl = pl;
}
void fire(){
if (liv > 0 and mun){
mun -= 1;
int hit = random(10);
printf("%d: ", hit);
printf("%s", pl[hit].get_name());
if (hit < 5 and pl[hit].live()){
pl[hit].hit();
printf("Player %s hit player %s!", name, pl[hit].get_name());
}
}
}
bool live(){
return liv;
}
void hit(){
liv -= 1;
}
char * get_name(){
return name;
}
private:
int liv, mun;
char name[100];
player *pl;
};
main(){
player pl[5];
char str[100];
int x;
for (x=0;x<5;x++){
sprintf(str, "%d", x + 1);
pl[x].Rename(str);
pl[x].set_group(pl);
}
pl[0].fire();
}
编译器 (TDM-GCC 4.9.2 32-bit) 编译代码并返回 0 个警告和 0 个错误。
当我运行程序时,我收到消息:classes.exe has encountered a problem and needs to close. We are sorry for the inconvenience.
我调试了一下,发现printf("%s", pl[hit].get_name());这行有问题(其实是调试行,后面的行确实有问题,但都是一回事)。我也认为访问 pl 是个问题。
我对 C 和 C++(尤其是 C+)比较陌生,我的主要编程语言是 Python,所以不要对我的错误笑太多。
【问题讨论】:
-
错误1:你不应该在你的随机函数中调用
srand(time(NULL));,因为如果你在一秒钟内多次调用它,你总是会得到相同的随机数。相反,您应该只设置一次种子。 -
pl = pl;并没有按照你的想法去做 -
pl = pl;变量名称在 c++ 中是免费提供的,不要为成员变量和参数回收pl名称;在这条指令中,哪个pl分配给了哪个pl?我不知道,也不想知道:只是使用不同的名称!
标签: c++ class oop private member