首页 > linux > linux-GCC编辑提示invalid initialization of non-const reference of type
2015四月14

linux-GCC编辑提示invalid initialization of non-const reference of type

自己写了个模块注册类,发现在window下正常,在GCC下编译就报上面的

invalid initialization of non-const reference of type

错误

查了下C++标准语法:

Initialization of a reference is trivial when the initializer is an lvalue (an object whose address you can take; see §4.9.6).
The initializer for a 'plain' T& must be an lvalue of type T. 
The initializer for a const T& need not be an lvalue or even of type T. 
In such cases (David''s notes: and only in such cases), [1] first, implicit type conversion to T is applied if necessary (see §C.6); [2] then, the resulting value is placed in a temporary variable of type T; and [3] finally, this temporary variable is used as the value of the initializer. 
Consider: 
    double& dr = 1;         // error: lvalue needed 
    const double& cdr = 1;  // ok 
The interpretation of this last initialization might be:
    double temp = double(1) ; // first create a temporary with the right value
    const double& cdr = temp; // then use the temporary as the initializer for cdr A temporary created to hold a reference initializer persists until the end of its reference’s scope. References to variables and references to constants are distinguished because the introduction of a temporary in the case of the variable is highly errorprone; an assignment to the variable would become an assignment to the – soon to disappear – temporary. No such problem exists for references to constants, and references to constants are often important as function arguments (§11.6).

解决方式:二选一 1.加上构造函数,默认构造函数不做任何初始化工作. 2.传参时加上const,这样才能启用系统默认的构造函数 代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class IDMReg;
typedef IDMReg* IDMRegPtr; 
class IDMReg
{
public:
	IDMReg(){}//1.
	virtual ~IDMReg(){}
};
class A
{
 
};
template<class T>
class  DMRegHelperT:public IDMReg
{
public:
	DMRegHelperT(){}
	~DMRegHelperT(){}
};
 
void Register(IDMReg&RegObj)//2.const也可加上
{
	int i=0;
}
 
int main(int argc, char *argv[])
{
	char sz[] = "Hello, World!";	//Hover mouse over "sz" while debugging to see its contents
	cout << sz << endl;	//<================= Put a breakpoint here
	Register(DMRegHelperT<A>());
	while (1)
	{
	}
	return 0;
}

文章作者:hgy413
本文地址:http://hgy413.com/2173.html
版权所有 © 转载时必须以链接形式注明作者和原始出处!

本文目前尚无任何评论.

发表评论