在学习谭浩强编的《C++面向对象程序设计》过程中碰到的两个问题。
第一个问题是:书中的例1.4题的程序原样如下,
#include <iostream>
using namespace std;
class Student
{private:
int num;
int score;
public:
void setdata()
{cin> > num;
cin> > score;
}
void display()
{cout < < "num= " < <num < <endl;
cout < < "score= " < <score < <endl;
}; (这一行的分号到底用不用加?为什么?)
};
Student stud1,stud2;
int main()
{stud1.setdata();
stud2.setdata();
stud1.display();
stud2.display();
return 0;
}
另一个问题:书中的例1.7 用一个函数求2个整数或3个整数中的最大者。其程序书中原样如下,
#include <iostream>
using namespace std;
int max(int a,int b,int c) //求3个整数中的最大者
{if (b> a) a=b;
if (c> a) a=c;
return a;
}
int max(int a, int b) //求两个整数中的最大者
{if (a> b) return a;
else return b;
}
int main( )
{int a=7,b=-4,c=9;
cout < <max(a,b,c) < <endl; //输出3个整数中的最大者
cout < <max(a,b) < <endl; //输出两个整数中的最大者
return 0;
}
该程序用到重载函数,现在要改用带有默认参数的函数,小弟想不出,请各位路过的高手指点指点,帮忙解答,万分感谢!
[解决办法]
struct
{
};
用分号
class
{
};
用分号
class member function
ClassName::ClassMemberFunction( )
{
.......
}
可不用!
int fn1()
{
return 0;
};;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
这对编译器来说完全正确。
这些应该说是没有用的 "; ",只是代表一条空语句。
[解决办法]
1、第一个分号可以不用加,这只是一条空语句,加在这里也不会影响程序编译及运行,一般情况下函数末不用加。
2、不是很清楚LZ的意思,要改成带默认参数的函数,可以直接把这样写int max(int a=0,int b=0,int c=0),函数体可以不变。
[解决办法]
该程序用到重载函数,现在要改用带有默认参数的函数??
LZ说的带默认参数的,意思就是比较三(两)个数中有一个是已经给出初始值的比如:
int max(int a,int b,int c=10);
[解决办法]
#define MIN_INT 0X80000000
int max(int a,int b,int c=MIN_INT) //第3个参数定义为最小的整数,则不影响前两个的结果.
{
if (b> a)
a=b;
if (c> a)
a=c;
return a;
}
main()
{
cout < <max(-10,10) < <endl;
cout < <max(10,20) < <endl;
cout < <max(30,10) < <endl;
cout < <max(-10,-100) < <endl;
cout < <max(-10,10,100) < <endl;
cout < <max(200,20,-300) < <endl;
cout < <max(30,10,20) < <endl;
cout < <max(-10,-100,-50) < <endl;
}