Geekband Week a 第一周作业遇到的问题

Geekband Week a 第一周作业遇到的问题1


本人刚接触C++,下面是写本周作业遇到的一些问题。作为自己的记录,也欢迎指正和讨论。

本周作业遇到的问题:

1.成员函数与带参内联函数的混淆:

class date
{
public:
    date (int y = 0,int m = 0, int d = 0) 
    : year(y) , month(m) , day(d)
    { }
    int get_year() const {return year;}
private:
    int year , month , day;
};

inline int
get_year(const date& x)
{
    return x.get_year();
 } 
 

如以上部分,定义date类后,在classbody内定义了get_year()函数,最初在操作符'>'函数内直接引用了get_year()函数,导致报错。
明确了成员函数自带this型指针以及成员函数的调用方式之后,在class body外定义了内联函数get_year(date& x) ,该函数以类date的引用为参数,作用域为全域。

2.this指针作为参数对类的data的访问方式:

既然在成员函数自带this指针参数,并指向调用该函数的类本身,那么对访问data的方式以下两种访问方式,哪一个更快呢?

inline bool
date::operator > (const date& x)
{
    int i = 0;
    if (year > x.year)
    // 1、直接访问data,与在class body内部书写成员函数一样
        i = 1;
    else if((this->year == x.year) && (this->get_month() > x.month))
        i = 1;    // 2、this指针访问data
    else if((this->year == x.year)&& this->get_month() == x.month&&(this->get_day() > x.day))
        i = 1;
    return i;
}

3.在classbody外定义常量成员函数的方法:
在函数声明后、分号前加 const

class date
{
public:
    date (int y = 0,int m = 0, int d = 0) : year(y) , month(m) , day(d)
    { }
    int get_year()const;
private:
    int year , month , day;
};

inline int
date::get_year()const
{
    return year;//get_year();
 } 

你可能感兴趣的:(Geekband Week a 第一周作业遇到的问题)