还没有弄明白为什么。自己的改了也没有成功,待解决
#include <vector>
#include <iostream>
using namespace std;
template <class T>
class Element{
public:
。。。
Element(const Element<T> &e);
int getDim() { return this->dim; }
。。。
private:
int dim;
。。。
};
。。。
在调用拷贝构造时,报错为“error: passing ‘const Element<int>’ as ‘this’ argument of ‘const std::vector<T, std::allocator<_Tp1> >& Element<T>::getDim() [with T = int]’ discards qualifiers”
2. 解决方案
因为this指针是不可改变的,为了确保其不变性,将getDim函数也定义为const的,即“int getDim() const { return this->dim; }”
本文探讨了一个关于C++模板类中拷贝构造函数使用的问题,具体表现为调用时出现错误提示,原因在于成员函数`getDim()`未正确声明为`const`。文中给出了修改建议:将该成员函数声明为`const`以确保`this`指针的不变性。
1493

被折叠的 条评论
为什么被折叠?



