写在前面:
对于平时遇到的一些小的问题,需要及时的记录下来,以防重复遇到再次的耗时间去想。
问题1:
struct node
{
int a, b;
};
int main()
{
node a(10,5);
return 0;
}
报错:error: no matching function for call to 'node::node(int&, int)'
原因其实很简答,就是没有注意。自定义的类或者结构体没有写带参数的构造函数的时候,编译器是不会那么智能的添加对应的构造函数,编译器只会提供默认的无参构造函数。
struct node
{
int a, b;
};
int main()
{
node a;//调用默认无参构造函数
cout << a.a << endl << a.b <<endl;
return 0;
}
输出:2686760 2686916
这里的a,b没有初始化所以是一个随机值。
struct node
{
static int a = 10;
};
error: ISO C++ forbids in-class initialization of non-const static member 'node::a'
c++不允许在类定义的内部初始化非常量的静态成员。
struct node
{
static int a;
};
int node::a = 10;
一定不要忘记类型名。
问题2:
struct node
{
int a, b;
node(int& x, const int& y):a(x),b(y) {}
};
int main()
{
node a(10,5);
return 0;
}
错误error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
在这里构造函数传递的是引用,传入的是常量,常量到非常量的转化编译器是不允许的,所以报错:类型’int’的非常量引用的类型’int’的右值的无效初始化。