猿问
下载APP

学习C++一疑问(有关函数定义位置的问题)?

书上面说可以在类定义外定义函数,但是小弟用VC试验的时候 发现却不可以
程序如下:这个是书上给出的 但是运行通不过
“void rectangle::assign(double len,double wide)
{
length=len;width=wide;
}”就是要定义的函数,如果将其写在类 rectangle定义中则可以运行 

程序:
#include<iostream.h>
class rectangle
{
protected:
double length;
double width;
public:
rectangle(){assign(0,0);}
rectangle(double len,double wide){assign(len,wide);}
double getLength(){return length;}
double getWidth(){return width;}
double getArea(){return length*width;}
};

void rectangle::assign(double len,double wide)
{
length=len;width=wide;
}

main()
{
rectangle rect;
double len,wide;
cout<<"enter length of rectangle:";
cin>>len;
cout<<"enter width of rectangle:";
cin>>wide;
rect.assign(len,wide);
cout<<"rectangle length="<<rect.getLength()<<"\n"
<<" width ="<<rect.getWidth()<<"\n"
<<" area ="<<rect.getArea()<<"\n";
return 0;
}

凤凰求蛊
浏览 167回答 2
2回答

慕神8447489

正确的程序为:#include<iostream.h>class rectangle{protected:double length;double width;public:rectangle::assign(double len,double wide);rectangle(){assign(0,0);}rectangle(double len,double wide){assign(len,wide);}double getLength(){return length;}double getWidth(){return width;}double getArea(){return length*width;}};rectangle::assign(double len,double wide){length=len;width=wide;}int main(){rectangle rect;double len,wide;cout<<"enter length of rectangle:";cin>>len;cout<<"enter width of rectangle:";cin>>wide;rect.assign(len,wide);cout<<"rectangle length="<<rect.getLength()<<"\n"<<" width ="<<rect.getWidth()<<"\n"<<" area ="<<rect.getArea()<<"\n";return 0;}在类定义外定义函数时需在类内做函数声明。另void rectangle::assign(double len,double wide) 类声明重复,这里rectangle是定义的类,是你需要的,所以void不要。还有main( )前必须有类声明,这里为int。

largeQ

将void rectangle::assign(double len,double wide){length=len;width=wide;}改为:inline void rectangle::assign(double len,double wide){length=len;width=wide;}试试加上inline的意思是:将rectangle函数作为类的内联函数
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答