C++ 报错集合

[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要写出非constconst两个函数,在实例化类时 调用者为所欲为,可能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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值