3.完成第9章的编程练习1,
连接查看细节
但要用正确的golf类声明替换那里的代码。
用带合适参数的构造函数替换 setgolf(golf&,const char*,int),以提供初始值。
保留 setgolf()的交互版本,但要用构造函数来实现它(
例如,setgolf()的代码应该获得数据,将数据传递给构造函数来创建一个临时对象,并将其赋给调用对象即*this)。
class golf
{
public:
golf(const char* name = "", int hc = 0);
~golf();
// interactive version:
// function solicits name and handicap from user
// and sets the members of g to the values entered
// returns 1 if name is entered, 0 if name is empty string
int setgolf(void);
// function resets handicap to new value
void sethandicap( int hc);
// function displays contents of golf structure
void showgolf(void)const;
private:
static const int Len = 40;
char fullname[Len];
int handicap;
};
我们在这里添加析构函数,也希望和大家一起学习,了解真正的析构函数
#if 1
#include<iostream>
#include<cstring>
#include<string>
#include"golf.h"
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::hex;
golf::golf(const char* name, int hc){
int numCh = strlen(name) + 1;
strcpy_s(fullname, numCh, name);
handicap = hc;
}
int
golf::setgolf(void){
cout << "输入名字:";
string strname;
getline(cin, strname);
if ("" == strname){
return 0;
}
cout << "输入差点:";
int n;
cin >> n;
cin.get();
if (!n) {
return 0;
}
*this = golf(strname.c_str(), n);
}
void golf::sethandicap(int hc){
handicap = hc;
}
void golf::showgolf(void)const{
cout << fullname << "\t" << handicap;
}
golf::~golf(){
cout << "Bye!\n";
cout << hex;
cout << "this address:" << this << endl;
}
#endif // 1
主函数执行
#pragma region 练习3
/*
*/
#if 1
#include <iostream>
#include"golf.h"
using namespace std;
int main()
{
const unsigned num = 4;
golf golfers[num];
unsigned numGolfers = 0;
while (numGolfers < num && golfers[numGolfers].setgolf()) {
++numGolfers;
}
for (unsigned i = 0; i < numGolfers; i++)
{
golfers[i].showgolf();
cout << endl;
}
cout << endl;
return 0;
}
#endif
#pragma endregion
看下有打印出来的效果,从这里可以看出this,指针的一个变化,和不变,临时变量的析构函数中打印出来的地址是一样的。
但是在申请的四个变量的this指针是