c++ - 关于一段带有模板、转换运算符和复制构造函数的代码的问题

标签 c++ templates c++11 operator-overloading copy-constructor

关于下面这段代码的两个问题:

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
}
  1. 为什么 inherit <int> b(3);导致 inherit 的复制构造函数?为什么复制而不是创建 inherit 的新实例使用默认构造函数从头开始?

  2. 为什么 b+5;导致转换运算符 operator T()以及为什么 c+k 不会发生这种情况?

最佳答案

  1. 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 的拷贝构造函数.

  1. 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/

相关文章:

c++ - std::vector<std::string> 的内容在分配为 R 值时是否会移动?

c++ - 在 C++ 中与 Repeater 中的委托(delegate) QML 组件交互

c++ - 替换已弃用的注册关键字 C++ 11

c++ - C++ 中带有纯虚方法的抽象模板类

正在缓存的 Django 自定义模板标签

c++ - 从 VS2013 到 VS2017 std::async 不启动新线程

c++ - 推导具有不同值类型的映射的返回类型

使用 #include 和包含保护在单独文件中继承 C++

c++ - 将多个 void* 复制到一个 vector 中

c++ - 为什么我会收到模板函数指针的链接器错误?