我试图理解我们在类里面做的这个例子,但遇到了一些麻烦......
对于一个类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 的变量是如何以及在哪里被考虑的?在上面的函数中,只有一个时间参数 labStart 被传入,因此 t2.mins t2.sec 占 labStarts 分钟和秒,(分别为 30 分钟和 0 秒)但是 labEnd 的变量在哪里(12,20,0) ?? (实例变量小时、分钟、秒)??
最佳答案
在您的函数中,this
是指向&labEnd
的指针。裸露的 secs
、mins
和 hrs
前面有一个隐含的 this->
。如果您显式写出 this->
,则三个变量声明变为:
int s = this->secs - t2.secs;
int m = this->mins - t2.mins - borrow;
int h = this->hrs - t2.hrs - borrow;
关于c++ - 理解 C++ 类和函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19580637/