inline关键字

基类如下:

class base  
{
public:
    base();
    virtual ~base();
  void Add(const char* pId, const char* pName);
  const char* GetId() const;   // 加inline
  const char* GetName() const; // 加inline
private:
  char m_szID[32];
  char m_szName[32];
};

派生类如下:

#include "base.h"

class course  :public base
{
public:
    course();
  virtual ~course(); 
  void Add(const char* pId, const char* pName, int iScore);
private:
  int  m_iScore;
};

派生类中隐藏了父类的add函数,派生类add函数实现如下:

void course::Add(const char* pId, const char* pName, int iScore)
{
  m_iScore = iScore;
  base::Add(pId, pName);
  cout << "Id:" << GetId() << " Name:" 
       << GetName() << " Score:" << m_iScore << endl;
}

如果我们把基类注释加inline关键字的函数加上关键字,那么派生类在使用时。会报这种错误:

course.obj : error LNK2001: unresolved external symbol "public: char const * __thiscall base::GetId(void)const " (?GetId@base@@QBEPBDXZ)
course.obj : error LNK2001: unresolved external symbol "public: char const * __thiscall base::GetName(void)const " (?GetName@base@@QBEPBDXZ)
Debug/Work2.exe : fatal error LNK1120: 2 unresolved externals
Error executing link.exe.

在链接course.obj的时候找不到基类的这两个函数,因为内联不产生函数调用,直接产生代码替换,所以,函数被编译器优化掉了!

我们用winhex打开base.obj的中间文件。查看是否有被名称粉碎后的函数名.搜索关键字Get:

 

posted @ 2013-05-14 23:16  0x苦行僧  阅读(145)  评论(0编辑  收藏  举报