2011-10-07 94 views
3

我从来没有用过它,只是在一篇文章中偶然发现了......我认为这将是相当于*x->y,但显然它不是。- > *运算符究竟是什么?

这里是我试过了,给了我一个错误:

struct cake { 
int * yogurt; 
} * pie; 

int main(void) { 
pie = new cake; 
pie->yogurt = new int; 
return pie->*yogurt = 4; 
} 
+2

你能显示一些上下文吗? –

+0

我发布了一个示例代码... – slartibartfast

+0

它主要用于方法指针和函数成员指针。 – Pubby

回答

4

它的使用,当你有指针成员函数。

当你有一个指向类的功能,你怎么称呼它以同样的方式,你会调用的任何成员函数

object.membername(...)

objectptr-> membername(...)

但是当你有一个成员函数指针时,需要一个额外的*。或 - >以便编译器明白接下来是变量,而不是要调用的函数的实际名称。

下面是一个如何使用它的例子。

class Duck 
{ 
public: 

    void quack() { cout << "quack" << endl; } 
    void waddle() { cout << "waddle" << endl; } 
}; 

typedef void (Duck::*ActionPointer)(); 

ActionPointer myaction = &Duck::quack; 

void takeDuckAction() 
{  
    Duck myduck; 
    Duck *myduckptr = &myduck; 

    (myduck.*myaction)(); 
    (myduckptr->*myaction)(); 
} 
+0

我明白了,所以它和':: *'一起用于非静态成员函数指针。谢谢。 – slartibartfast

+0

@myrkos是的,更新了一些答案,使其更清晰 – MerickOWA

+2

也适用于指针(成员变量)。 –

3

它定义了一个pointer to a member

In an expression containing the –>* operator, the first operand must be of the type "pointer to the class type" of the type specified in the second operand, or it must be of a type unambiguously derived from that class. MSDN

+1

请多解释一下? – slartibartfast

+1

它当然没有定义它,成员指针的定义看起来像'Type Class :: *' –

+0

@ K-ballo:单词的选择不好。过去几天我一直喝咖啡因(每天几杯),所以我的大脑就像一个炒鸡蛋。 – 2011-10-07 01:04:32

0

。*和 - > *运算符将指向类或结构的成员函数。下面的代码将展示如何使用一个简单的例子*运营商,如果你改变了行: Value funcPtr = &Foo::One;Value funcPtr = &Foo::Two;显示的结果将更改为1000,因为该功能是inValue*2

例如Taken From Here

#include <iostream> 
#include <stdlib.h> 

class Foo { 
    public: 
    double One(long inVal) { return inVal*1; } 
    double Two(long inVal) { return inVal*2; } 
}; 

typedef double (Foo::*Value)(long inVal); 

int main(int argc, char **argv) { 
    Value funcPtr = &Foo::One; 

    Foo foo; 

    double result = (foo.*funcPtr)(500); 
    std::cout << result << std::endl; 
    system("pause"); 
    return 0; 
}