【发布时间】:2016-01-30 21:47:00
【问题描述】:
关于下面这段代码的两个问题:
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
}
为什么
inherit <int> b(3);会导致inherit的复制ctor?为什么要使用默认 ctor 从头开始复制而不是创建inherit的新实例?为什么
b+5;会导致转换运算符operator T()以及为什么c+k不会发生?
【问题讨论】:
-
main必须在 C++ 中返回int。 -
b+5有效,因为5是一个 int 并且有一个内置的operator+。string是一个模板,模板化的operator+都不匹配inherit<string>和string。 -
但是
operator+@BoPersson也内置了string,为什么还要用b+5;进行转换? -
@kuh 看看
operator+上的std::basic_string是如何定义的。也让我们偷懒:包括令人惊讶的输出(应该是全部),你认为它意味着什么,以及你明确期望什么。我的心理 C++ 编译器不完善,复制/粘贴/编译是可行的。 -
field(1+t)导致inherit<string>甚至无法为我编译。你能确保你的例子可以编译吗?用魔杖盒?
标签: c++ templates c++11 operator-overloading copy-constructor