Two questions about the following piece of code:
template <class T> class A {
protected:
T j;
public:
A(T k) :j(k) {cout << *this;}
~A() { cout << *this; }
A(const A<T> &a) {
j = a.j;
cout << *this;
}
virtual void print() const {cout << j << ' ';}
friend ostream &operator << (ostream &os, const A<T> &a) {
a.print();
return os;
}
operator T() { return j;}
};
template <class T> class inherit:public A<T> {
T field;
public:
inherit(const T&t) :A<T>(t), field(1+t) {
cout << *this;
}
void print() const {
A<T>::print();
cout << field << ' ';
}
};
int main(){
inherit <int> b(3);
inherit <string> c("asdf");
string k="str";
c + k;//error no operator +
b + 5;//no error
}
-
Why does
inherit <int> b(3);
leads to the copy ctor ofinherit
? Why copy instead of making a new instance ofinherit
from scratch using the default ctor? -
Why does
b+5;
leads to the conversion operatoroperator T()
and why it doesn't happen withc+k
?
Aucun commentaire:
Enregistrer un commentaire