Fork me on GitHub

C++虚函数的使用示例

本文通过一段简短的示例程序,展示在c++中virtual函数的使用方式

示例程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <memory>

class A {
public:
void Setup(){
std::cout << "setup in A" << std::endl;

layerSetup();
reshape();
}

virtual void layerSetup() { std::cout <<"virtual layerSetup in A" <<std::endl; };
virtual void reshape(){ std::cout <<"virtual reshape in A" <<std::endl; };
};

class B:public A{
void layerSetup(){
std::cout << "layerSetup in B" << std::endl;
}

void reshape(){
std::cout << "reshape in B" << std::endl;
}
};

int main(){
std::shared_ptr<B> ptr(new B);
ptr->Setup();

std::shared_ptr<A> pc(new A);
pc->Setup();

B insb;
insb.Setup();

A insa;
insa.Setup();

return 0;
}

输出:

setup in A
layerSetup in B
reshape in B

setup in A
virtual layerSetup in A
virtual reshape in A

setup in A
layerSetup in B
reshape in B

setup in A
virtual layerSetup in A
virtual reshape in A

您的鼓励是我持之以恒的动力