c++ - 理解 C++ 类和函数调用

标签 c++ function class

我试图理解我们在类里面做的这个例子,但遇到了一些麻烦......

对于一个类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 的指针。裸露的 secsminshrs 前面有一个隐含的 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/

相关文章:

c++ - 同一类中的多个 Operator() 重载

c++ - “[Warning] extra tokens at end of”,同时编译我的代码

c# - 为什么绑定(bind)到结构不起作用?

c++ - 为什么引用类型成员会导致隐式声明的复制赋值运算符被删除

postgresql - 在 PostgreSQL 中授予执行函数 pg_start_backup 不起作用

mysql - 如何在 MySQL 中创建一个函数来在表中添加元素?

function - Lua 返回多个值作为参数

Python - 类方法多进程安全吗?

c++ - 如何让 Foo* 迭代器指向 Foo 的 vector ?

c++ - DirectShow - 如何确定流是否有效(C++)