【问题标题】:understanding c++ class and function calls理解 C++ 类和函数调用
【发布时间】:2013-10-25 03:34:40
【问题描述】:

我试图理解我们在课堂上做的这个例子,但遇到了一些麻烦......

对于 Time 类,该类的实例由 hrs、mins secs 组成

所以

Time labStart(10,30,0);
Time labEnd (12,20,0);

 (labEnd-labStart).printTime() //I'm not concerned with the printTime function

const Time Time::operator - (const Time& t2) const {

    int borrow=0;
    int s=secs-t2.secs;

    if (s<0) {
     s+=60;
     borrow=1;
    }

    int m=mins-t2.mins2-borrow;
     if (m<0) {
     m+=60;
     borrow=1;
    }
    else 
      borrow=0;

    int h= hrs-t2.hrs-borrow;
     if (h<0) {
     h+=24;

     Time tmp=Time(h,m,s);
     return tmp;
}

所以如果我们同时通过了 labEnd 和 labStart,我被告知 (labEnd-labStart) ~ labEnd.operator-(labStart)

我不明白 labEnd 的变量是如何以及在哪里考虑的?在上面的函数中,只传入了一个 Time 参数,labStart,因此 t2.mins t2.sec 占 labStarts 分钟和秒,(分别为 30 分钟和 0 秒)但是 labEnd 的变量在哪里(12,20,0) ?? (实例变量小时,分钟,秒)??

【问题讨论】:

    标签: c++ function class


    【解决方案1】:

    在你的函数中this 是一个指向&amp;labEnd 的指针。裸露的secsminshrs 提及在它们前面有一个隐含的this-&gt;。如果你明确写出this-&gt;'s 三个变量声明变成:

    int s = this->secs - t2.secs;
    int m = this->mins - t2.mins - borrow;
    int h = this->hrs  - t2.hrs  - borrow;
    

    【讨论】:

      【解决方案2】:
      labEnd - labStart
      

      相当于:

      labEnd.operator -(labStart)
      

      所以labEnd在成员函数中就是this,它的成员变量可以像普通变量一样访问。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-22
        • 2014-05-04
        • 2012-01-03
        • 2012-03-15
        • 1970-01-01
        • 2011-01-05
        相关资源
        最近更新 更多