简体   繁体   English

我怎样才能参考C ++中的函数?

[英]How can I refer to what called a function in C++?

I was wondering if there is a way in C++ to know what called a function? 我想知道在C ++中是否有办法知道什么叫做函数? Like the this keyword in Java or JavaScript. 就像Java或JavaScript中的this关键字一样。

For example, I have a function called insert, which inserts an item into a linked list, I want the linked-list that called those the function insert to call two other functions. 例如,我有一个名为insert的函数,它将一个项插入到一个链表中,我希望调用那些函数insert的链表调用另外两个函数。 How would I do that? 我该怎么办?

I have this right now, is this valid? 我现在有这个,这有效吗?

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;
}

For historical reasons , this is a pointer. 由于历史原因this是一个指针。 Use -> instead of . 使用->而不是. .

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;
}

Usually it is not needed to use this-> at all; 通常根本不需要使用this-> ; you can just do if(is_present(i)) . 你可以做if(is_present(i))

this works in c++ the same as it does in Java. this在c ++中的工作方式与在Java中的工作方式相同。 The only difference is that you need to use this-> instead of this. 唯一的区别是你需要使用this->而不是this. this is a pointer than therefor you cannot use the dot operator to access it's members. this是一个指针,因此您不能使用点运算符来访问它的成员。

why don't you just call the other functions in linked_list::insert(int) ? 为什么不直接调用linked_list::insert(int)的其他函数? And no, it is not valid, you should put this -> something instead of this.something 不,它是无效的,你应该把this -> something ,而不是this.something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM