Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ non class scope replacement for this.x = x;

In C++ I can do this in classes:

class MyClass {
    public:
        int number;
        void SetNumber(int number);
};

void MyClass::SetNumber(int number)
{
    this->number = number;
}

But what about this:

int number;

void SetNumber(int number)
{
    //What do I do here?
}

This problem is because there isn't a "this" for the scope, there are only "this"s for classes. Any ideas?

like image 213
Robert Martin Avatar asked Dec 05 '25 07:12

Robert Martin


2 Answers

It sounds like you are looking for

::number = number;

This assumes that the top number is declared at the global scope. If it isn't, we need more context.

like image 65
NPE Avatar answered Dec 07 '25 02:12

NPE


I think the very OBVIOUS solution is to NOT name the argument of a function the same as a global variable. Change either number to aNumber ("a" for "argument") or change number to gNumber ("g" for "global"). Or make the argument num, n, nr, x, kerflunk or anything other than number. [And this really applies to member functions too, in my opinion].

like image 43
Mats Petersson Avatar answered Dec 07 '25 04:12

Mats Petersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!