调用重载运算符 - >在编译时解决了吗?

Bre*_*t81 3 c++ operator-overloading

当我尝试编译代码时:(注意:func和func2不是拼写错误)

struct S
{
    void func2() {}
};

class O
{
public:
    inline S* operator->() const;
private:
    S* ses;
};

inline S* O::operator->() const
{
    return ses;
}

int main()
{
    O object;
    object->func();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

报告编译错误:

D:\code>g++ operatorp.cpp -S -o operatorp.exe
operatorp.cpp: In function `int main()':
operatorp.cpp:27: error: 'struct S' has no member named 'func'
Run Code Online (Sandbox Code Playgroud)

看来调用"operator->"的重载函数是在编译期间完成的吗?我添加了"-S"选项仅用于编译.

Ash*_*ain 10

是的,它被视为普通的函数调用,它只是由重载的运算符调用.编译器在编译时检查一切是否有效.C++与动态语言不同,如果它p->mynonexistantfunction()是函数的有效名称,它等待运行时才能运行,如果函数名不存在,编译器将在编译时拒绝代码.

在这种情况下,它看起来像一个拼写错误,S有一个函数,func2()但你的代码调用func().