Skip to content

ask: C++的虚函数可以是内联函数吗 #223

Answered by Mq-b
Dofes asked this question in Q&A
Discussion options

You must be logged in to vote

调用发生在运行时,是动态绑定

这种词语都是描述的语言层面的意思(当然了这个运行时也莫名),编译器懂的多了去了,别说内联了,编译期直接算出结果都可以,但是这不是语言层面的事情,这些话一堆人分不清。

#include <iostream>

struct X {
    virtual int f(int){return 0;}
};

struct Y :X {
    virtual int f(int a) { return a * a; }
};

int main() {
    X* x = new Y;
    int ret = x->f(10);
    std::cout<<ret<<'\n';
}

开个优化,随便都是直接出虚函数运行结果

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
1 reply
@rsp4jack
Comment options

Comment options

You must be logged in to vote
2 replies
@Mq-b
Comment options

@Mq-b
Comment options

Answer selected by Dofes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
enhancement New feature or request category: daily 卢瑟日经
3 participants
Converted from issue

This discussion was converted from issue #222 on January 01, 2024 15:18.