inline  向 compiler 保證 , 你不管看到幾次 這個 function , 它的內容都一樣 !!

還有建議 compiler 將內容 "插入" 呼叫它的 function , compiler 可以選擇接受 or not !!

static function 是每個 cpp 可以有自己的 function ,  所以一個執行檔可能會有多個 defination 的 function !!!!

source1 :  這個 .h 可以用 #pragma once 或是 #ifndef  #endif  兩種方式避免重複定義 , 但是 ,  Print() 那邊

你還是得加上 inline 保證 Print() source 只有一份 , 換得 compiler 的信任 !!!

#pragma once

//#ifndef   _MARS_H_
//#define  _MARS_H_

#include <iostream>
class People
{
private:
    int i ;
public:
    People(int inum_=10):i(inum_){}
    int getnum() const { return i ; }
    int getnum()  { return i ; }
    inline  void Print() ;
} ;

void People::Print()
{
    std::cout << getnum() << std::endl ;
}

void xxx(int) ;
void yyy(int) ;

//#endif

 

mars1.cpp :

 

#include "stack.h"

static void zzz() ;

void zzz()
{
    std::cout << "static in mars1.cpp" << std::endl ;
}


int main()
{
    yyy(100) ;

    People p(12345) ;
    p.Print() ;

    zzz() ;
    std::cout << "================================" << std::endl ;
}

 

mars.cpp

#include "stack.h"

static void zzz() ;

void zzz()
{
    std::cout << "static in mars.cpp" << std::endl ;
}

void xxx(int i)
{
    std::cout << "xxx is called:" << i << std::endl ;
    zzz() ;
}

void yyy(int i)
{
    std::cout << "yyy is called " << std::endl ;
    xxx(i) ;
}

 

output :

yyy is called
xxx is called:100
static in mars.cpp
12345
static in mars1.cpp
================================

 

xxx 呼叫 zzz()  是呼叫  stack.cpp 的 zzz() function ,  main 呼叫的 zzz() 則是 stack1.cpp 裡面的 ,

所以 ,  static  每個 cpp 都能有相同名字的  function defination ,  1.cpp 有 static zzz() , 2.cpp 也有 static zzz()

如果是 1.cpp 的 function 呼叫 zzz() , 則 該 1.cpp 的 zzz() 被執行  ,  就這樣而已 !!

 

arrow
arrow
    全站熱搜

    hedgezzz 發表在 痞客邦 留言(0) 人氣()