C++ 无法从常量类转换此指针<;T>;上课<;T>&;

C++ 无法从常量类转换此指针<;T>;上课<;T>&;,c++,reference,constants,copy-constructor,C++,Reference,Constants,Copy Constructor,我正在尝试实现一个简单的复制构造函数: template<typename T> MyClass<T>::MyClass(const MyClass<T> &other) { MyIterator<T> it = other.begin(); //... }; 模板 MyClass::MyClass(常量MyClass和其他){ MyIterator it=other.begin(); //... }; 成员函数体中的这一行会生

我正在尝试实现一个简单的复制构造函数:

template<typename T>
MyClass<T>::MyClass(const MyClass<T> &other) {
  MyIterator<T> it = other.begin();
  //...
};
模板
MyClass::MyClass(常量MyClass和其他){
MyIterator it=other.begin();
//...
};
成员函数体中的这一行会生成以下错误:

无法将此指针从常量类转换为类&


我用const_cast尝试了一些东西,但没有成功。

您的
begin
方法显然是非const的,但是您尝试在const对象上调用它。

这真是一件好事,您不能这样做!很少有情况下需要使用
const\u cast
,因此一般来说,像这里这样,这不是正确的做法

other
是一个
const
对象,因此它的
begin()
应该返回一个const迭代器。而不是

MyIterator<T> it = other.begin();
MyIterator it=other.begin();
使用

MyConstIterator it=other.begin();

它应该可以工作(如果您定义了常量迭代器)。

请告诉我们MyIterator,MyIterator可能正在尝试使用非常量迭代器。这就是错误所在。我认为const关键字必须放在构造函数声明的末尾。构造函数不能是
const
,因为它正在创建对象,所以要修改它。
MyConstIterator<T> it = other.begin();