call function in class
i want to change the "value" when run my app. but when i call RS232::PackageRecived in "RS232.cpp" i revived This Error :
Error 1 er开发者_如何学Cror C2352: 'RS232::PackageRecived' : illegal call of non-static member
//////////////////////////////////////////// RS232.cpp FILE
#include "RS232.h"
void RS232::PackageRecived()
{
value =123;
}
void TryCallPackageRecived()
{
RS232::PackageRecived(); // my compiler error is here
}
int RS232::Connect()
{
TryCallPackageRecived();
}
RS232::RS232(void)
{
}
RS232::~RS232(void)
{
}
//////////////////////////////////////////// RS232.h File
class RS232
{
public:
int value;
int Connect();
void PackageRecived();
RS232(void);
~RS232(void);
};
//////////////////////////////////////////// Main.cpp File
#include "RS232.h"
RS232 RS;
int main()
{
RS.Connect();
}
Your function, "TryCallPackageRecived()" is not a member of the RS232 class. It's trying to call a member function of RS232 that is not static. This is not allowed. When you want to call a non-static member function you need to call it on a particular object.
In this case, you could do:
RS.PackageRecived();
If you want to allow for multiple objects, you could modify your TryCallPackageRecived function to take a pointer to the RS232 object:
void TryCallPackageRecived(RS232 *ptr)
{
if(ptr != 0)
ptr->PackageRecived();
}
... more code ...
int RS232::Connect()
{
TryCallPackageRecived(this);
}
That's because PackageRecived
is not a static method and you can't call non-static methods without an object.
Either make it a static method (but it depends on your logic) or Call it directly since you are inside this class anyway.
void TryCallPackageRecived()
{
PackageRecived(); // my compiler error is here
}
The obvious way to fix this would be to add TryCallPackageRecived()
to your RS232
class:
//////////////////////////////////////////// RS232.h File
class RS232
{
public:
int value;
int Connect();
void PackageRecived();
void TryCallPackageRecived();
RS232();
~RS232();
};
//////////////////////////////////////////// RS232.cpp
// [...]
void RS232::TryCallPackageRecived()
{
PackageRecived();
}
// [...]
精彩评论