几个C++的小问题,麻烦大虾门帮下忙
Q1:不知道是哪里出了问题,运行不出来
#include "stdafx.h"
#include "iostream"
using namespace std;
class Dog
{
public:
Dog(int initialAge=0,int initialWeight=5);
~Dog();
int GetAge(){return itsAge;}
void SetAge(int age){itsAge=age;}
int GetWeght(){return itsWeight;}
void SetWeight(int weight){itsWeight=weight;}
private:
int itsAge,itsWeight;
};
Dog::Dog(int initialAge=0, int initialWeight=5);
{
itsAge=initialAge;
itsWeight=initialWeight;
}
Dog::~Dog()
{
}
int main()
{Dog jack(2,10);
cout<<"Jack is a dog who is"<<jack.GetAge()<<"years old and"<<jack.GetWeght()<<"pounds weight"<<endl;
jack.SetAge(7);
jack.SetWeight(20);
cout<<"now jack is"<<cout<<jack.GetAge()<<"years old and"<<jack.GetWeght()<<"pounds weight."<<endl;
return 0;
}
Q2:代码中const在这里起到什么作用?
#include "stdafx.h"
#include "iostream"
using namespace std;
class Rectangle
{public:
Rectangle(int top,int left ,int bottom,int right);
~Rectangle(){}
int GetTop()const {return itsTop;}
int GetLeft()const {return itsLeft;}
int GetBottom()const {return itsBottom;}
int GetRight()const {return itsRight;}
void SetTop(int top){itsTop=top;}
void SetLeft(int left){itsLeft=left;}
void SetBottom(int bottom){itsBottom=bottom;}
void SetRight(int right){itsRight=right;}
int GetArea()const;
private:
int itsTop;
int itsLeft;
int itsRight;
int itsBottom;
};
Rectangle::Rectangle(int top, int left, int bottom, int right)
{
itsTop=top;
itsLeft=left;
itsBottom=bottom;
itsRight=right;
}
int Rectangle::GetArea()const
{
int Width=itsRight-itsLeft;
int Height=itsTop-itsBottom;
return(Width*Height);
}
int main()
{
Rectangle MyRectangle(100,20,50,80);
int Area=MyRectangle.GetArea();
cout<<"Area:"<<Area<<endl;
return 0;
}
[解决办法]
第一个程序有两处错误,都在Dog构造函数:
Dog::Dog(int initialAge=0, int initialWeight=5);
{
itsAge=initialAge;
itsWeight=initialWeight;
}
1:第一行后的分号去掉
2:你在类的定义体里面声明时使用了默认实参,那么在定义的时候就不用再指定它的值了,把=0和=5去掉就好了。
[解决办法]
A1:语法有误,修改一下,就可以
带形参默认值,在声明是写了默认值,定义时就不用再写,否则报错,网上找到一篇比较详细的文章,有兴趣就看,我就瞄了一眼。
http://www.cnblogs.com/tziyachi/archive/2012/03/15/2397627.html
另外函数定义的时候,不要再()后加分号
A2:成员函数加const后,调用这个函数的对象的成员变量不可以修改