关于c++ this指针的问题~~在线等~~

来源:百度知道 编辑:UC知道 时间:2024/06/19 08:23:13
下面程序,关于疑惑的地方 我用汉语注释表明了。。请大家来帮我回答呀~先谢谢了

#include <iostream>
using std::cout;
using std::endl;

class CBox // Class definition at global scope
{
public:
// Constructor definition
CBox(double lv = 1.0, double bv = 1.0, double hv = 1.0)
{
cout << endl << "Constructor called.";
m_Length = lv; // Set values of
m_Width = bv; // data members
m_Height = hv;
}

// Function to calculate the volume of a box
double Volume()
{
return m_Length*m_Width*m_Height;
}

// Function to compare two boxes which returns true (1)
// if the first is greater than the second, and false (0) otherwise
int Compare(CBox xBox)
{
return this->Volume() > xBox.Volume();//这里的this->Volume()返回的值为什么是 ci

if(cigar.Compare(match)) 由这行决定

Compare是由cigar对象调用的 (Compare前的.的前面是cigar)
Compare函数中的this会指向cigar对象 this->Volume()
当然是 cigar 成员调用之后返回的值

if(cigar.Compare(match))

你程序写的.
在这里match只是做为该函数的一个参数,而这个成员函数是cigar的,所以this是指向cigar. this->volume()也就是 cigar.volume() 一个意思了

我说自己的理解,我讲的不是术语,多多包涵~~

cigar.Compare(match)

此时match对于Compare函数而言只是作为一个参数进来的,而这是Compare函数是cigar调用的,那类默认有的一个this指针肯定给函数的调用者(“自家人”)cigar,怎么会给一个“外来人”呢?