如何在C ++中使用弱函数 [英] How to use weak function in C++
本文介绍了如何在C ++中使用弱函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在C ++中的类中使用弱函数.下面是我写的:
I am trying to use weak function in a class in C++. Below is what I wrote:
#include <stdio.h>
#include <iostream>
class A {
public:
void func(int argc, char *argv[]) __attribute__((weak));
};
// optional definition:
#if 0
void A::func(int argc, char *argv[]) {
printf("In func()\n");
for(int aa = 0; aa < argc; aa++){
printf("arg %d = %s \n", aa, argv[aa]);
}
}
#endif
int main(int argc, char *argv[]) {
A a1;
if (a1.func){
a1.func(argc, argv);
} else {
printf("func() not available\n");
}
return 0;
}
但这会导致以下编译错误:
But this gives below compilation error:
main.cpp: In function ‘int main(int, char**)’:
main.cpp:21:16: error: cannot convert ‘A::func’ from type ‘void (A::)(int, char**)’ to type ‘bool’
if (a1.func){
^
如果我将func()移到类之外,并使用gcc而不是g ++,它可以正常编译并按预期工作.有人可以告诉我是什么问题.基本上,我想实现仅在某些类函数可用时(可选功能)而不在cpp文件中使用编译器标志的情况下调用它们.
If I move the func() outside a class and use gcc instead of g++, it compiles fine and works as expected. Can someone please tell what's the problem. Basically I want to achieve calling some class functions only if they are available (an optional feature) without using Compiler flags in cpp file.
推荐答案
C ++为此提供了一种标准机制.无需链接器技巧.
C++ has a standard mechanism for this. No need for linker tricks.
class Base {
public:
virtual void func(int argc, char *argv[])
{
printf("func() not available\n");
}
};
class A : public Base {
public:
#if 0
void func(int argc, char *argv[]) override;
#endif
};
#if 0
void A::func(int argc, char *argv[]) {
printf("In func()\n");
for(int aa = 0; aa < argc; aa++){
printf("arg %d = %s \n", aa, argv[aa]);
}
}
#endif
int main(int argc, char *argv[]) {
A a1;
a1.func(argc, argv);
}
这篇关于如何在C ++中使用弱函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文