【发布时间】:2016-06-03 21:44:26
【问题描述】:
我不确定术语重载是否适用于此,但我想做的是继承一个类,然后在没有任何参数的情况下调用它的成员函数,以便从当前类成员变量自动继承参数.用代码更容易解释,所以我把它贴在这里:
#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()),这是意料之外的。
【问题讨论】:
-
你不能让例子更简单吗?例如单例和模板与您的问题有什么关系?
-
你可以忽略它,它确实与问题无关,但我出于个人喜好在我的调试/测试代码中实现了它。与 Singleton 相关的所有内容都可以忽略,您仍然可以轻松理解我希望实现的总体思路,我很抱歉 :)
标签: c++ class inheritance default-arguments