了解 C++ 类和函数调用
understanding c++ class and function calls
我试图理解我们在课堂上做的这个例子,但遇到了一些麻烦......
对于类时间,此类的实例由小时、分钟秒组成
所以
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
的指针。裸露的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;
labEnd - labStart
相当于:
labEnd.operator -(labStart)
因此labEnd
this
成员函数中,并且可以像访问普通变量一样访问其成员变量。
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销