[with T = int]’ is private within this context
原因:class
成员默认私有,可能是class
定义里忘了写public
了。
template<class T>
class AAA
{
// public:
AAA(const T& dat):data(dat) { }
AAA() { }
aaa();
bbb();
private:
T data;
};
error: passing ‘const AAA’ as ‘this’ argument discards qualifiers [-fpermissive]
原因:const
对象调用了非const
成员,一般class
要写出非const
和const
两个函数,在实例化类时 调用者为所欲为,可能const AAA<int> aaa(1); aaa.non_const_func();
如果没有const成员函数则报错。
template<class T>
class AAA
{
public:
AAA(const T& dat):data(dat) { }
AAA() { }
void aaa();
// void aaa () const; // 或许要添加这个
int bbb();
private:
T data;
};
error: cannot bind non-const lvalue reference of type ‘xxx’ to an rvalue of type ‘xxx’
通常是引用&
到了常量
或者临时变量
,而引用&
不能绑定到常量或者临时对象
,
#include<iostream>
using namespace std;
template<class T>
class AAA
{
public:
AAA(const T& dat=T()):data(dat) { }
void func(T& x) // 加const T& x就没有错误了
{
cout << x << endl;
}
T data;
};
int main()
{
AAA<int> aaa;
int a = 100;
const int b = 100;
// error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'
// aaa.func(AAA<int>(100).data); // error
// aaa.func(100); // error
aaa.func(a); // ok
// error: binding reference of type 'int&' to 'const int' discards qualifiers (丢弃限定符)
// aaa.func(b); // error
return 0;
}