您的位置:首页 > 编程语言 > C语言/C++

[c++学习]关于const使用的疑惑

2018-02-06 04:00 260 查看

[c++学习]关于const使用的疑惑

 如代码行所标注的地方的const和&的用法和其含义不是很明白,希望已经掌握此用法的同学帮我解答一下:-P,对了书中还提到了保留setgolf()的交互版本,但要用构造函数来实现它(例如,setgolf()的代码应该获得数据,将数据传递给构造函数来创建一个临时对象,并将其赋给调用对象,即*this)。请问这句话能顺带解释一下吗?尤其是“要用构造函数来实现它”。

//ex10.3
//golf.h
#ifndef GOLF_H_
#define GOLF_H_
class Golf
{
private:
static const int Len = 40;
char fullname[Len];
int handicap;
public:
Golf();
Golf(const char * name, int hc);
const Golf & setgolf(const Golf & g); //这里的const 和&号不是很明白
void showgolf() const;
};
#endif
//golf.cpp
#include <iostream>
#include <cstring>
#include "golf.h"
Golf::Golf()
{
strcpy(fullname, "No Name");
handicap = 0;
}
Golf::Golf(const char *name, int hc)
{
strcpy(fullname, name);
handicap = hc;
}
const Golf &Golf::setgolf(const Golf &g) //这里的const 和&号不是很明白
{
strcpy(fullname, g.fullname);
handicap = g.handicap;
return *this;
}
void Golf::showgolf() const
{
std::cout << "Golfer: "<< fullname << "\n";
std::cout << "Handicap: " << handicap << "\n\n";
}
//main
#include <iostream>
#include "golf.h"
int main()
{
Golf golger1("Ann Birdfree", 5);
golger1.showgolf();
Golf golger2;
golger2.setgolf(golger1);
golger2.showgolf();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C const 学习