我不确定术语重载是否适用于这里,但我想做的是继承一个类,然后调用它的不带任何参数的成员函数,这样参数就会自动从当前类成员变量继承.用代码更容易解释,所以我会把它贴在这里:
#include <iostream>
template <typename T>
struct Singleton {
static T & Instance() {
static T instance;
return instance;
}
T * operator -> () const {
return &Instance();
}
};
struct SFoo : Singleton<SFoo> {
void Print( int a = 0 ) {
printf( "%d\n", a );
}
};
struct SBar : SFoo {
const static int b = 42;
friend void Print( int a = b); // <- Should call SFoo::Print() with integer b as the argument
};
int main() {
using Foo = Singleton<SFoo>;
using Bar = Singleton<SBar>;
Foo()->Print( 123 ); // Should print: 123
Bar()->Print(); // Should print: 42
getchar();
return 0;
}
我对继承比较陌生,似乎无法理解这么简单的一段代码。现在的结果是打印 123
和 0
(SFoo::Print()
的默认参数),这不是预期的。
最佳答案
void Print(int a = b) { SFoo::Print(a); }
让它发挥作用,正如您所指出的,它也可以是:
void Print() { SFoo::Print(b); }
因为我们不需要接受 int
的两个版本。
另一方面,您声明了一个friend
(这是一个非成员函数)。程序中的任何地方都没有调用它(Bar()->Print();
调用 SFoo::Print
),并且你没有收到链接器错误,因为缺少定义。
关于C++用参数重载友元类函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37623915/