了解 C++ 类和函数调用

understanding c++ class and function calls

本文关键字:函数调用 C++ 了解      更新时间:2023-10-16

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

对于类时间,此类的实例由小时、分钟秒组成

所以

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 的变量是如何以及在何处考虑的?在上面的函数中,只有一个时间参数被传入,labStart,所以t2.mins t2.sec占labStartmins和secs(分别为30分钟和0秒),但是labEnd的变量(12,20,0)在哪里?(实例变量小时、分钟、秒)??

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

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

相当于:

labEnd.operator -(labStart)

因此labEnd this成员函数中,并且可以像访问普通变量一样访问其成员变量。