[英]Passing member function to function pointer
我必須將成員函數的函數指針傳遞給另一個類。 我無法編譯它,我得到“未定義的引用classB :: classB(classA :: *)(std :: shared_ptr)”錯誤。 有人可以幫我弄這個嗎?
謝謝。
classA{
string functionA(share_ptr<int>);
void functionB(){
classB* ptr = new classB(&classA::functionA);
}
}
//in other .h file
classA; //forward declaration
classB{
classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}
你寫的代碼是我的代碼:
classA{
string functionA(share_ptr<int>);
void functionB(){
classB* ptr = new classB(&classA::functionA);
}
}
這里:
share_ptr
應該是shared_ptr
。
在類定義的末尾有一個缺少的分號。
然后,
//in other .h file
classA; //forward declaration
classB{
classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}
這里:
有三個左括號(
但是只有兩個右括號)
。
在類定義的末尾缺少分號。
您詢問鏈接錯誤,但您的代碼甚至不應該編譯。
當你說“我無法讓它編譯”似乎是正確的。
然后,當您聲明“我得到[未定義的引用...]”時,這是一個謎:在您顯然使用的工具鏈中,當編譯失敗時,不應調用鏈接器。
總之,該問題包含一些不正確的信息和任何答案(例如,您尚未定義函數的假設,或者您在某處定義了函數但忘記鏈接的假設,或者您正在報告錯誤的假設)從構建別的東西而不是你的代碼,等等)將是純粹的猜測。
請發布一個完整的小程序,編譯並說明鏈接錯誤。
干杯&hth。,
從表面上看,這看起來像是一個前瞻性聲明問題。 嘗試宣告classA::functionB
為你做了,然后定義classA::functionB
的定義后classB
。
只是為了咯咯地笑,即使您說它是為您編譯的,也要回答這個問題...
// In a.hpp
#include "b.hpp" // you need to include this because you will not
// be able to call B's constructor in your functionB() method
class A
{
public:
string functionA ( shared_ptr<int> ); // IIRC, needs to be public to call it
// from B's constructor.
// can be public/protected/private depending on where it's called ...
void functionB () {
B * ptrB = new B ( &A::functionA );
}
};
和
// In b.hpp
// Forward declare class A
class A;
// To make the constructor of B cleaner, use a typedef.
typedef string (A::*IntPtrToStrFn) ( shared_ptr<int> );
class B
{
public:
B ( IntPtrToStrFn fnptr );
};
就樣式和代碼可讀性而言,這是可怕的-將兩個類聯系在一起,並散發出些許代碼味道。 需要查看某種適配器類或其他設計模式才能使這兩個類一起工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.