1. 问题描述
#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; }”