Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 类用作模板参数时丢失继承的方法_C++_Templates_Inheritance - Fatal编程技术网

C++ 类用作模板参数时丢失继承的方法

C++ 类用作模板参数时丢失继承的方法,c++,templates,inheritance,C++,Templates,Inheritance,可能重复: 我在用作模板参数的类中使用继承方法时遇到问题。如下图所示: class D { }; class A { public: void f( D &d ){}; }; class B: public A { public: void f( int ) {}; }; template<typename F> class C { public: void doit() { D d; f->f(d); };

可能重复:

我在用作模板参数的类中使用继承方法时遇到问题。如下图所示:

class D
{
};

class A
{
public:
        void f( D &d ){};
};

class B: public A
{
public:
        void f( int ) {};
};

template<typename F>
class C
{
public:
        void doit() { D d; f->f(d); };
        F *f;
};

int main()
{
        C<B> cb;
        cb.doit();
}
D类
{
};
甲级
{
公众:
f(D&D){}无效;
};
B类:公共A
{
公众:
空f(int){};
};
模板
C类
{
公众:
void doit(){dd;f->f(D);};
F*F;
};
int main()
{
C cb;
cb.doit();
}
这就是我试图编译它时得到的结果:

g++ testtemplate.cpp 
testtemplate.cpp: In member function ‘void C<F>::doit() [with F = B]’:
testtemplate.cpp:28:   instantiated from here
testtemplate.cpp:21: error: no matching function for call to ‘B::f(D&)’
testtemplate.cpp:14: note: candidates are: void B::f(int)
g++testtemplate.cpp
testtemplate.cpp:在成员函数“void C::doit()[带F=B]”中:
testtemplate.cpp:28:从此处实例化
testtemplate.cpp:21:错误:没有用于调用“B::f(D&)”的匹配函数
testtemplate.cpp:14:注意:候选项是:void B::f(int)
但是,如果删除void f(int){}方法,编译器将找到原始方法f(D&D)。看起来原来的方法被新方法遮住了。我想知道原因。

你可以这样做

class B: public A
{
public:
    using A::f;
    void f( int ) {};
};

基本上隐藏所有同名的基类方法。

是的,方法
B.f
隐藏
A.f
。如果希望它在
B
中可用,则需要使用指令:

class B: public A
{
public:
    using A::f;
    void f( int ) {};
};

派生类的成员将隐藏具有相同名称的任何基类成员。为了使
A::f
B
中可用,您需要使用声明:

class B: public A
{
public:
    using A::f;         // <--- add this
    void f( int ) {};
};
B类:公共A类
{
公众:
使用A::f;//查看