How would I keep track of a float from an external class?
Say I have some class I refer to in main that takes in a float like this:
class SomeClass {
SomeClass(float a) {
}
int someMethodDoingSomethingWith_a() {
// perform something on _a
}
float _a;
}
In my main class, I will be constructing this SomeClass with a float value that will be constantly changing through the course of its process.
Whenever I perform some of the methods in SomeCl开发者_如何学Pythonass, it will be using its float _a, but I want it to be the updated float (whatever it currently is in main).
What would you recommend I do, use pointers? Please suggest what I could do.
Here is different code from Nawaz one. It is more safe way of doing same.
class SomeClass {
public:
SomeClass(float a) {
}
int someMethodDoingSomethingWith_a() {
// perform something on _a
}
float get_a()
{
return _a;
}
void set_a(float f)
{
_a=f;
}
private:
float _a;// _a is not reference anymore!!!!!!
}
int main()
{
SomeClass S(5.7);
//Now you can get and set a's value with get_a and set a
S.set_a(7.1);
return 0;
}
To show difference from Nawaz's solution let's consider following code, assuming, that we are storing reference in class as Nawaz do.
std::shared_ptr<SomeClass> somefunction()
{
float x =7;
return std::shared_ptr<SomeClass>(new SomeClass(x));
}
This function will return pointer to function which will have reference to something, which already removed from memory.
And Here is another problem of such code:
SomeClass A(25); // A._a is referring to garbage.
Then define it like:
class SomeClass {
SomeClass(float & a) : _a (a) {
}
//....
float & _a;
}
int main()
{
float x;
SomeClass inst(x);
}
Now, if you change x
in main()
, then _a
in SomeClass
will be updated accordingly. But note that this automatic change will be reflected only in inst
instance of SomeClass
.
精彩评论