开发者

C++ Templates: Why does not this work? [duplicate]

开发者 https://www.devze.com 2023-01-24 01:28 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: C++ method only visible when object cast to base class?!
This question already has answers here: Closed 12 years ago.

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* 开发者_JAVA技巧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?


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 a using directive to the derived class:

class StrVector : public Vector<String> {
public:
   using Vector<String>::Add;
   ...
}


Nope. You are hiding all the Add functions ov Vector by declaring Add functions in class StrVector. The compiler is issuing an error, and it is right: int Add(String&) is not accessible.


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.


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 from Vector<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>.

0

精彩评论

暂无评论...
验证码 换一张
取 消