Hallo!
Now I've tried out for quite a long time how to access the []-operator from
a base class. But I cannot find out how to do this. Well, it's an example
from "Think in C++".
So, I guess I need some help from any real C++ programmer.
Greetings, Ulf
// 14.9 Inherit a class StringVector from vector<void*> and redefine the
push_back( ) and operator[] member
// functions to accept and produce string*. What happens if you try to
push_back( ) a void*?
//StringVector.cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class StringVector: public vector<void*> {
public:
void push_back(string* str){cout << "My_push_
back called\n";vector<void*>::push_back(str);}
// following code does not work!!
string* operator[](int i) {
string* t= (string*)(vector<void*>&)this[i]; //wrong! What can I do?
return (t);
}
};
int
main(){
StringVector s;
string *str1 = new string("Hallo");
string *str2 = new string("Welt");
s.push_back(str1);
s.push_back(str2);
cout << *(string*)s[0] << endl;
cout << *(string*)s[1] << endl;
return 0;
}