ERROR NO.2
内置函数inline。类体中定义的函数功能一般规模较小,系统调用类为定义的函数的过程需要的时间开销是比较大的,为了减少系统调用函数的时间开销,如果在类体智能光定义的函数不包括循环等控制结构,C++会自动将它们作为内置函数。
内置函数的作用是将函数实现的代码替代声明的地方,以减小系统调用类外函数的时间开销。
今天使用是遇到了问题,代码如下
//head.h #include <iostream> #include <string> using namespace std; class Student { public: inline void Display(); inline void set_vlaue(); protected: private: int num; string name; char sex; }; //main.cpp #include "head.h" using namespace std; int main() { Student stu; stu.set_vlaue(); stu.Display(); return 0; } //student.cpp #include "head.h" void Student::set_vlaue() { cin >> num; cin >> name; cin >> sex; } void Student::Display() { cout << "num:" << num << endl; cout << "name:" << name << endl; cout << "sex:" << sex << endl; }
在编译是出现如下错误:
1>mian_s3_3.obj : error LNK2019: 无法解析的外部符号 "public: void __thiscall Student::Display(void)" (?Display @Student @@QAEXXZ),该符号在函数 _main 中被引用
1>E:\VCworkspace\C++_exercise\lx_3\Debug\shiyan3_3.exe : fatal error LNK1120: 1 个无法解析的外部命令
解决方法:
仔细检查发现inline函数使用时函数实现必须也在定义类的文件中。