为什么我不能覆盖默认的拷贝构造函数和赋值运算符与C ++中的模板版本 [英] Why can't I override the default copy constructor and assignment operator with template versions in C++

查看:130
本文介绍了为什么我不能覆盖默认的拷贝构造函数和赋值运算符与C ++中的模板版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问此问题有关使用模板版本重载复制构造函数和赋值运算符,并考虑涉及问题的混淆(因为它似乎是一个编译器错误),我想我会尝试只有模板副本构造函数和模板分配操作符看看会发生什么。但是它们被编译器完全忽略。

  struct BaseClass 
{
public:
BaseClass(){}

template< typename T>
BaseClass(const T& a_other)
{
int i = 0; //为未命中的断点
}

模板< typename T>
BaseClass& operator =(const T& a_other)
{
int i = 0; //未命中的断点
return * this;
}

};

struct MyClass:public BaseClass
{
};

int main()
{
MyClass i,j;
i = j;

return 0;
}

为什么我不能超越模板版本的默认值答案将是默认值是更好的匹配,但我想模板版本也作为默认值)?

解决方案

  template< typename T> 
BaseClass(const T& a_other)

首先,构造函数。这是一个模板化的构造函数。



复制构造函数应该是这样:

  BaseClass(const BaseClass& a_other)

区别?



请注意,模板构造函数未定义复制构造函数。编译器将仍然为您生成默认的复制构造函数,而不是实例化模板化的构造函数。



复制赋值的相同参数。 / p>

I asked this question about overloading the copy constructor and assignment operator with template versions and considering the confusion involving around the question (since it seems to be a compiler bug), I thought I'd try with only template copy constructor and template assignment operator to see what happens. But they are completely ignored by the compiler.

struct BaseClass
{
public:
  BaseClass() {}

  template<typename T>
  BaseClass(const T& a_other)
  {
    int i = 0; // for break point which is not hit
  }

  template<typename T>
  BaseClass& operator= (const T& a_other)
  {
    int i = 0; // for break point which is not hit
    return *this;
  }

};

struct MyClass : public BaseClass
{
};

int main()
{
  MyClass i, j;
  i = j;

  return 0;
}

Why can't I over-ride the defaults with template versions (I suspect the answer will be the defaults are a better match but I would like the template versions to act as defaults as well)? And is there anything I can do to make sure the template versions are called instead of the defaults?

解决方案

template<typename T>
BaseClass(const T& a_other) 

First of all, this is not a copy-constructor. It is rather a templated constructor.

The copy-constructor should be this:

BaseClass(const BaseClass & a_other)

Notice the difference?

Note that the templated constructor doesn't define copy-constructor. The compiler will still generate a default copy-constructor for you, instead of instantiating the templated constructor.

Same argument for copy-assignment.

这篇关于为什么我不能覆盖默认的拷贝构造函数和赋值运算符与C ++中的模板版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆