Is the call to the overload operator-> permitted at compile time?

when I tried to compile the code: (note: func and func2 are not sealed)

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

compilation error reported:

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'

It seems that the overloaded function "operator->" is being called at compile time? I added the -S option for compilation only.

+3
source share
5 answers

object->func()is just syntactic sugar object->operator->()->func()for custom types. Because O::operator->()it does S*, it requires the existence of a method S::func()at compile time.

+1
source

, , . , . ++ , , , p->mynonexistantfunction() , , .

, S func2(), func().

+10

struct S func2(), func().

int main() { O object; object->func2(); return 0; }

+3

, .

, , ,

S* foo() { ... }

(foo())->func();

.

+2

++ . ( ) . .

, , , .* ->* ( - ). . - ( ), ->*, , . - ( ) .

+2
source

Source: https://habr.com/ru/post/1747040/


All Articles