关于下面这段代码的两个问题:
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
的复制构造函数?为什么复制而不是创建inherit
的新实例使用默认构造函数从头开始?为什么
b+5;
导致转换运算符operator T()
以及为什么c+k
不会发生这种情况?
最佳答案
- Why does
inherit <int> b(3);
leads to the copy ctor of inherit? Why copy instead of making a new instance of inherit from scratch using the default ctor?
首先,它不会导致复制构造函数,实例实际上从头开始。
没有使用默认构造函数,因为您没有调用默认构造函数。默认构造函数将使用空参数列表调用(除了,在这种情况下,您还必须省略括号以避免令人烦恼的解析):
inherit <int> b; // this would call the default constructor
如果您将参数传递给构造函数,则会调用非默认构造函数。 inherit <int> b(3);
导致调用 inherit(const T&)
在这个模板实例中是 inherit(const int&)
.它不是 inherit
的拷贝构造函数.
- Why does b+5; leads to the casting operator operator T()
因为没有operator+(const inherit<int>&, int)
也没有定义类似的成员函数。因此,重载决策寻找可以隐式转换操作数的替代方案。碰巧的是,一个内置的 operator+(int, int)
存在,并且 inherit<int>
可以隐式转换为 A<int>
(因为它是一个基地)和 A<int>
可以转换为 int
(因为类型转换运算符(operator))。因此,该运算符(operator)最终被调用。
and why it doesn't happen with c+k?
首先,您甚至无法实例化 inherit <string>
因为构造函数试图将一个 int 添加到没有有效重载的参数字符串中。
现在,假设构造函数是固定的,所以 inherit<string>
可以存在,c + k
似乎仍然不起作用。我怀疑这是因为字符串需要比 int
更多的转换因为它不是原语,并且您已经达到了用户定义的转换序列可以具有的最大深度。您可以显式转换 inherit<string>
至 string
缩短转换顺序:
static_cast<std::string>(c) + k; // this works
关于c++ - 关于一段带有模板、转换运算符和复制构造函数的代码的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35107522/