“этот” указатель в классе

Я полагаю, что эквивалентный Java Iterable<String>. Хотя String[] не реализует его, можно циклично выполниться по элементам так или иначе:

String[] strings = new String[]{"this", "that"};
for (String s : strings) {
    // do something
}

при реальной необходимости в чем-то, что реализует Iterable<String>, можно сделать это:

String[] strings = new String[]{"this", "that"};
Iterable<String> stringIterable = Arrays.asList(strings);
6
задан Jonathan 22 October 2009 в 21:44
поделиться

4 ответа

No, there is no real difference, it is simply a scope qualifier. However, suppose a method

void SetFoo( Foo foo )
{
    this->foo = foo;
}

where this->foo is a private member. Here it allows you to take a parameter with the same name as a class/instance variable.

12
ответ дан 8 December 2019 в 03:27
поделиться

In most cases there is no difference. But there are situations where it makes a difference:

class foo
{
    int i;
    void bar() {
        int i = 3;
        i; // refers to local i
        this->i; // refers to the member i
    }
};

Also, with templates you may need to qualify a member with this-> so that name lookup is delayed:

template<typename T>
struct A
{
    int i;
    T* p;
};

template<typename T>
struct B : A<T>
{
    void foo() {
        int k = this->i; // here this-> is required
    }
};

A compiler that properly does the "two phase lookup" will complain in case you remove "this->" that it doesn't know what i is supposed to be. "this->" tells it that it's a member from a base class. Since the base class depends on a template parameter, lookup is delayed until the class template is instantiated.

16
ответ дан 8 December 2019 в 03:27
поделиться

This was kind of asked and answered about C# here and I think that the answer (at least mine) is the same. It is preference.

0
ответ дан 8 December 2019 в 03:27
поделиться

Я считаю, что использование этого делает мой код более читабельным, но нет никаких причин, по которым это нужно. Если вы посмотрите на ассемблерный код, который генерирует ваш компилятор, он должен быть функционально (и обычно буквально) идентичным.

В основном, когда функция вызывается, ей передается скрытый аргумент this , который затем используется чтобы выяснить, какие переменные где. Если вы используете переменные напрямую, без this -> , вы ничего не делаете, кроме использования некоторого синтаксического сахара.

1
ответ дан 8 December 2019 в 03:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: