【发布时间】:2017-11-27 17:32:32
【问题描述】:
长话短说,我在这里想要的是在基类中声明一个模板类型并能够访问该类型 A<T> 以便基类 B 包含它并且派生类 C 能够以C::A<T> 访问它。我确实尝试在class B 中声明一个int,并且可以从派生的C 类中访问C::int,这是错误!
||In constructor ‘D::D()’:|
|74|error: no match for ‘operator=’ (operand types are ‘A<C*>’ and ‘A<B*>’)|
|4|note: candidate: A<C*>& A<C*>::operator=(const A<C*>&)|
|4|note: no known conversion for argument 1 from ‘A<B*>’ to ‘const A<C*>&’|
这是编译的代码(注释A<B*> i; 并取消注释A<C*> i; 以获取错误)。
#include <iostream>
//class with a template parameter
template <class a>
class A
{
private:
int somevalue;
public:
A(){}
~A(){}
void print()
{
std::cout<<somevalue<<std::endl;
}
};
//1. could forward declare
class C;
class B
{
protected:
A<B*> i;
//2. and then use
//A<C*> i;
public:
B(){}
~B(){}
A<B*> get()
{
return i;
}
/*
//3. use this return instead
A<C*> get()
{
return i;
}
*/
};
//specialization of B that uses B's methods variables
class C : public B
{
protected:
public:
C(){}
virtual ~C(){}
void method()
{
B::i.print();
}
};
//class D that inherits the specialization of C
class D : public C
{
private:
A<B*> i;//works
//4. but I want the inherited type to work like
//A<C*> i;// so that the type C* is interpreted as B*
public:
D()
{
this->i = C::i;
}
~D(){}
};
///////////////////////////////////////////////////////////////////////
int main()
{
D* d = new D();
delete d;
return 0;
}
【问题讨论】:
-
"这将解决整个问题,但它不是可移植的,也不像 C++。"解释一下?
-
我不想在每次使用该类时都声明该类名。考虑到我希望在不知道其内容的情况下将头文件存储在某处。
-
这是 MyTemplate
和 MyTemplate 类型长期以来的最爱,与继承问题无关吗?我实际上无法理解你的问题。它非常冗长且杂乱无章,您的示例中的代码比您需要的要多。 -
很抱歉,我实际上并不了解您的目标是什么,所以我无法告诉您如何更改代码以适应它。我可以告诉你,你不需要这种行为来实现你的目标......但根据上面的例子,我不知道哪种选择最适合你。我似乎也找不到骗子,虽然我知道我过去见过很多次。
-
@pandoragami 不,不是。
A是您在代码中创建的类模板(“这就是我的全部!”)。如果您有其他一些实际代码,则需要发布。
标签: c++ templates inheritance derived-class