-3

I've tried to do a reference to a member variable, and understood that it does not work. Are there any way to do this? If not, is there a way to not constantly write "(* this)." ?

#include <iostream>
#include <string>

class Test
{
private:
    std::string str_m;

    void doSomething()
    {
        std::string& str = (*this).str_m;      // does not work
        std::cout << str << '\n';
    }

public:
    Test(std::string str): str_m(str)
    {
        (*this).doSomething();
    }

};

int main()
{
    Test test{"aaa"};
    return 0;
}

VS compiler gave me: error C3867: 'Test::doSomething': non-standard syntax; use '&' to create a pointer to member

Fenix FVE
  • 53
  • 4

1 Answers1

3

I've tried to do a reference to a member variable, and understood that it does not work. Are there any way to do this?

Yes:

struct Test {
    std::string str_m;
    void doSomething()
    {
        std::string& str = str_m;
    }
};

[If not], is there a way to not constantly write "(* this)." ?

It is not clear from where you got the idea that you would have to write (*this).member. If you want to use this, then please write this->member, but there is no need to do this within the scope of the class (there are rare exceptions) and commonly it is frowned upon in favor of simply writing member.

PS: The error you report is from different code, not the one you posted.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185