C++模板:为什么这不起作用?
可能的重复:
C++ 方法仅在对象转换为基类时可见?!
我有以下代码:
class String {
char* _Text;
public:
String( const char* s ) {
int iLen = strlen(s);
_Text = new char [iLen+1];
strcpy( _Text, s );
}
};
template<typename T>
class Vector {
public:
int Add( T* pItem ) { return 0; }
int Add( const T* pItem ) { return 0; }
int Add( T& pItem ) { return 0; }
};
class StrVector : public Vector<String> {
public:
int Add( char* pItem ) { return 0; }
int Add( const char* pItem ) { return 0; }
};
void main()
{
String s;
StrVector v;
v.Add( s ); <-------------
}
v.Add( s );
行应该调用 Vector::Add(T& pItem)
,对吧?
Possible Duplicate:
C++ method only visible when object cast to base class?!
I've the follow code:
class String {
char* _Text;
public:
String( const char* s ) {
int iLen = strlen(s);
_Text = new char [iLen+1];
strcpy( _Text, s );
}
};
template<typename T>
class Vector {
public:
int Add( T* pItem ) { return 0; }
int Add( const T* pItem ) { return 0; }
int Add( T& pItem ) { return 0; }
};
class StrVector : public Vector<String> {
public:
int Add( char* pItem ) { return 0; }
int Add( const char* pItem ) { return 0; }
};
void main()
{
String s;
StrVector v;
v.Add( s ); <-------------
}
The line v.Add( s );
should call Vector::Add(T& pItem)
, right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
派生类中的
Add
方法 隐藏基类中定义的方法。如果您希望基类的
Add
不被隐藏,您可以向派生类添加一个using
指令:The
Add
methods in the derived class hide the methods defined in the base class.If you want the base class's
Add
to not be hidden, you can add ausing
directive to the derived class:没有。您可以通过在
StrVector
类中声明Add
函数来隐藏Vector
上的所有Add
函数。编译器发出错误,这是正确的:int Add(String&)
不可访问。Nope. You are hiding all the
Add
functions ovVector
by declaringAdd
functions in classStrVector
. The compiler is issuing an error, and it is right:int Add(String&)
is not accessible.我猜你所说的“不起作用”的意思是对
Add
的调用无法编译(没有合适的候选者,或类似的东西)。StrVector 中声明的
Add
方法隐藏了其基类中的方法。有关完整说明,请参阅命名空间和接口原理。I guess what you mean by "not working" is that the call to
Add
doesn't compile (no appropriate candidate, or something similar).The
Add
methods declared in StrVector hide the ones from its base class. See Namespaces and the Interface Principle for a complete explanation.你从未给 Vector 一个实际的模板参数,只是说它是一个模板。您需要有
template
。接下来,StrVector
需要从Vector
继承,尽管我实际上不知道为什么要继承它。当然,在实际代码中,您将使用
std::vector
。You never gave Vector an actual template argument, just said that it was a template. You need to have
template<typename T>
. Next,StrVector
needs to inherit fromVector<char*>
, although why you're inheriting from it I don't actually know.Of cousre, in actual code, you'd use a
std::vector<std:string>
.