问题描述
Visual Studio给出了这个奇怪的错误:C6001:使用未初始化的内存“ Rect”。
#include<iostream>
#include<cstring>
using namespace std;
class Rectangle
{public:
int length,width;
int Area(int length,int width)
{
return length * width;
}
};
int main()
{
Rectangle d1;
d1.length = 5;
d1.width = 10;
cout << "d1 area=" << d1.length * d1.width << endl;
Rectangle Rect;
Rect.Area(Rect.length,Rect.width);
return 0;
}
这是什么意思以及如何解决?
解决方法
此声明中声明的对象Rect
Rectangle Rect;
具有未初始化的数据成员length
和width
。
您将这些未初始化的数据成员作为参数传递给成员函数Area
。
Rect.Area(Rect.legth,Rect.width);
所以通话没有意义。
您可以写个例子
Rectangle Rect = { 5,10 };
std::cout << Rect.Area(Rect.legth,Rect.width) << '\n';
请注意,函数Area应该是静态成员函数,或者应该使用对象的数据成员length
和width
。
要么应该这样声明
static long long int Area(int length,int width)
{
return static_cast<long long int>( length ) * width;
}
或喜欢
long long int Area() const
{
return static_cast<long long int>( length ) * width;
}