3

I am making a text-based RPG with C++ and I'm having the same error pop up time and again, and I'm sure I'm doing something fundamentally wrong, but I don't know what. Searches turned up the solution to the specific compiler error, but not anything I can use to fix the code I'm writing.

Question I want answered: How do I use pointers to enable communication of variables between separate functions? In other words, how can I use pointers to point to a variable's value so that I can use and manipulate that value in a function in which it was not declared?

TL;DR version: I'm trying to make my "exp" int variable communicate with outside functions using pointers. I get the error "ISO C++ forbids comparison between pointer and integer [-fpermissive]"

Long version: Here's a bit of the code where I'm having problems:

In file charlvl.cpp:

...
int lvl = 1;
int *exp = 0;//value I want communicated to main()
int str = 0;
int vit = 0;
...

in file fight.cpp (main.cpp):

...
//you've just killed a monster

cout << "\nThe monster drops to the ground." << endl;
cout << "You gained " << expValue << " experience!" << endl;
&exp += expValue;//&exp is the character's experience.

//expValue is the exp gained upon monster death
//*exp (from charlvl.cpp) is the value I want to communicate to here. 

It was not declared here, but in charlvl.cpp. How do I establish communication between the declared variable in charlvl.cpp and main() without having to resort to using global variables?

4

2 回答 2

2

如果将exp定义为全局指针,就不用考虑通信的事情了,直接在不同的函数中使用就可以了,但是使用方式是错误的。

&exp += expValue;

应该改为

*exp += expValue;

因为*意味着将指针的内容提供给我。

顺便说一句,尝试不将 exp 定义为指针也可能有效。

int exp = 0; exp += expValue;

这一切都基于exp一个全局变量或全局指针。

如果您在这样的函数中定义了它:

void func()
{
   int *expPtr = 0;
   int exp = 0
}

你想在另一个功能中使用它

void use()
{
   // trying to use expPtr or exp.

}

我知道的方法是:

1、使用本地var并在中返回func(),但要注意返回的var只是一个副本。

int func()
{
   int exp = 0;
   exp++;
   return exp;
}

2、使用本地指针并为其分配内存,然后返回指针或将新内存分配给全局指针。但是要小心内存泄漏,不使用就需要删除。

int * func()
{
   int *expPtr = 0;
   expPtr = new int(2);
   return expPtr;
}
于 2012-11-26T02:11:24.807 回答
0

你已经把&and*操作符弄糊涂了。*把一个int*变成一个int,而&把一个int*变成一个int**

这就是你想要的:

(*exp) += expValue;

您可能需要考虑使用引用。

于 2012-11-26T02:01:49.487 回答