练习7.34:如果我们把第256页Screen类的pos的typedef放在类的最后一行会发生什么情况?
答:显示pos没有被声明。
练习7.35:解释下面代码的含义,说明其中的Type和initVal分别使用了哪个定义。如果代码存在错误,尝试修改它。
typedef string Type;
Type initVal();//这个Type对应外围的typedef string Type;
class Exercise{
public:
typedef double Type;
Type setVal(Type);//这两个type对应类里面的typedef double Type
Type initVal();//对应类里面的typedef double Type,//这里也有错误,initVal没有定义
private:
int val;
};
Type Exercise::setVal(Type parm){//第一个Type由于不在类里,所以会对应应外围的typedef //string Type;括号里Type对应类里面的typedef double //Type,因此发生了错误。
val = parm + initVal();
return val;
}
改正方法:
ExerciseType Exercise::initVal() {}
Exercise::Type Exercise::setVal(Exercise::Type parm){
val = parm + initVal();
return val;
}
见云盘程序 练习7.35.cpp
练习7.35
/*
*练习7.35
*2015/7/14
*问题描述:练习7.35:解释下面代码的含义,说明其中的Type和initVal分别使用了哪个定义。如果代码存在错误,尝试修改它。
typedef string Type;
Type initVal();//这个Type对应外围的typedef string Type;
class Exercise{
public:
typedef double Type;
Type setVal(Type);//这两个type对应类里面的typedef double Type
Type initVal();//对应类里面的typedef double Type,//这里也有错误,initVal没有定义
private:
int val;
};
Type Exercise::setVal(Type parm){//第一个Type由于不在类里,所以会对应应外围的typedef //string Type;括号里Type对应类里面的typedef double //Type,因此发生了错误。
val = parm + initVal();
return val;
}
改正方法:
Exercise::Type Exercise::initVal() {}
Exercise::Type Exercise::setVal(Exercise::Type parm){
val = parm + initVal();
return val;
}
*功能:修改程序
*作者:Nick Feng
*邮箱:nickgreen23@163.com
*
*/
#include <iostream>
#include <vector>
using namespace std;
typedef string Type;
Type initVal();
class Exercise{
public:
typedef double Type;
Type setVal(Type);
Type initVal(){ return 1.0;}
private:
int val;
};
Exercise::Type Exercise::setVal(Exercise::Type parm){
val = parm + initVal();
return val;
}
int main()
{
Exercise a;
cout << a.setVal(1) << endl;
return 0;
}