Re: [問題] inline 的內部運作疑惑
purpose 大 後半段的文章還蠻讓人感興趣的,
查了一下 weak function, vc 這部份似乎沒 gcc 來得好
// weak.h
#ifndef _WEAK_H_
#define _WEAK_H_
#ifdef __GNUC__
#define WEAK __attribute__((weak))
#endif
void interface();
#endif
// impliement.c
#include "weak.h"
#include <stdio.h>
WEAK void weak_func(){ puts("[implement.c] default weak function"); }
void interface(){weak_func();}
// main.c
#include <stdio.h>
#include "weak.h"
WEAK void weak_func() { puts("[main.c] weak_func override.");}
int main()
{
interface();
return 0;
}
---
gcc 下,main 裡面之 weak_func 拿掉時,調用的是 impliement.c 裡之 weak_func
加上去時調用的是 main.c 裡之定義,這等於在包 library , 直接開一個後門,
讓其他 coder 下去改,這部份目前 VC 也辦不到 (以後改的機會可能也不大 )
http://0rz.tw/Tw9hw
要搞 weak function, 似乎還是搭配 macro 較穩
---
myTest.h
#ifndef _MY_TEST_H_
#define _MY_TEST_H_
#include <cmath>
typedef double (*pFunc)(double, double);
#ifndef _USER_FUNCTION_
inline double fitness(double x, double y) { return
sin(x)*sin(y)*sqrt(fabs(x*y));}
#endif
class Foo{
private:
pFunc m_FitnessFunction;
public:
Foo(pFunc func) : m_FitnessFunction(func){};
inline double Cal(double x, double y) {return m_FitnessFunction(x, y);}
};
#endif
main.cpp
#include <iostream>
#include <cmath>
#define _USER_FUNCTION_
inline double fitness(double x, double y) {return x*y;}
#include "myTest.h"
int main()
{
Foo obj(fitness);
std::cout << obj.Cal(10.0, 10.0) << std::endl;
return 0;
}
----
code 長得醜倒是真的 , 上面這例子也可能直接繼承 Foo 改寫 fitness 較乾脆。
--
No matter how gifted you are,
alone, can not change the world.
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 180.177.78.41
※ 編輯: tropical72 來自: 180.177.78.41 (10/26 04:52)
→
10/26 09:52, , 1F
10/26 09:52, 1F
→
10/26 09:54, , 2F
10/26 09:54, 2F
→
10/26 09:56, , 3F
10/26 09:56, 3F
→
10/26 21:51, , 4F
10/26 21:51, 4F
討論串 (同標題文章)
完整討論串 (本文為第 3 之 3 篇):