c/c++ 类的成员函数在内部定实现和外部实现有什么区别?

1 #include <iostream>
2 using namespace std;
3 class Student;
4 class Teacher {
5 public:
6 void educate (Student* student);
7 void reply (const string& answer) {
8 m_answer = answer;
9 }
10 private:
11 string m_answer;
12 };
13 class Student {
14 public:
15 void ask (const string& question,Teacher* teacher) {
16 cout << "问题:" << question << endl;
17 teacher->reply ("不知道!");
18 }
19 };
20 void Teacher::educate (Student* student) {
21 student->ask ("什么是this指针?", this);
22 cout << "答案:" << m_answer << endl;
23 }
24 int main (void) {
25 Teacher teacher;
26 Student student;
27 teacher.educate (&student);
28 return 0;
29 }
此程序中,如果将educate函数放在类内部实现就编译不过,由此引发我的疑问:内部实现和外部实现有什么区别?谢谢!

第一, 代码在内部不过是因为你的参数用到student类型,那个时候student类型还没有了,程序怎么能过呢。
第二,外部实现一般都是实现的virtual函数,这相当于一个接口。
C++经典的就是封装 继承 多态
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-10-27

    代码在内部不过是因为你的参数用到student类型,那个时候student类型还没有了,程序怎么能过。

    外部实现一般都是实现的virtual函数,这相当于一个接口,C++经典的就是封装,继承,多态。

    声明和定义分开是个好习惯,特别是在一个大的工程项目当中,就算是内联最好是定义成inline显示的方式。目前必然使用的场景就是成员模板函数必须得定义在里面(大部分编译器)。

相似回答