【问题标题】:How can I refer to what called a function in C++?如何引用 C++ 中的函数?
【发布时间】:2012-11-16 00:44:25
【问题描述】:

我想知道 C++ 中是否有办法知道什么叫做函数?就像 Java 或 JavaScript 中的 this 关键字一样。

例如,我有一个名为 insert 的函数,它将一个项目插入到链表中,我希望调用这些函数 insert 的链表调用其他两个函数。我该怎么做?

我现在有这个,有效吗?

bool linked_list::insert( int i )
{
    bool inserted = false;

    if( this.is_present(i) ) /* function is_present is defined earlier checks if an int is already in the linked-list. */
    {
        inserted = true // already inside the linked-list
    }
    else
    {
        this.Put( 0, i ); /* function Put is defined earlier and puts an int in a linked-list at a given position (first param.). */
        inserted = true; // it was put it.

    }
return inserted;
}

【问题讨论】:

  • 您的术语有点不正确。链表不调用insertinsert 在链表上被调用。该函数被其他使用它的函数调用。

标签: c++ algorithm linked-list


【解决方案1】:

对于historical reasonsthis 是一个指针。使用-> 而不是.

bool linked_list::insert(int i) {
    bool inserted = false;

    if(this->is_present(i)) {
        inserted = true; // fixed syntax error while I was at it.
    } else {
        this->put(0, i); // fixed inconsistent naming while I was at it.
        inserted = true;
    }
    return inserted;
}

通常根本不需要使用this->;你可以做if(is_present(i))

【讨论】:

    【解决方案2】:

    this 在 c++ 中的工作方式与在 Java 中的工作方式相同。唯一的区别是您需要使用this-> 而不是this. this 是一个指针,因此您不能使用点运算符来访问它的成员。

    【讨论】:

      【解决方案3】:

      为什么不直接调用linked_list::insert(int) 中的其他函数呢?不,它是无效的,你应该把this -> something而不是this.something

      【讨论】:

        猜你喜欢
        • 2016-02-18
        • 2016-08-18
        • 1970-01-01
        • 1970-01-01
        • 2010-11-27
        • 2020-03-14
        • 1970-01-01
        • 2010-11-27
        • 1970-01-01
        相关资源
        最近更新 更多