4124人加入学习
(13人评价)
C++编程系列 第二季函数和类

制作于2018.4.2

价格 免费

this指针:每一个对象都能通过this指针来访问自己的地址。在成员函数内部,它可以用来指向调用对象。

有时候方法可能涉及到两个对象,在这种情况下就需要使用this指针。

 

//Cuboid.h

#pragma once

#ifndef CUBOID_H_
#define CUBOID_H_
class Cuboid
{
private:
	double length_;
	double width_;
	double height_;

public:
	Cuboid(double length, double width, double height);
	Cuboid();
	~Cuboid();
	double volume() { return length_ * width_*height_; };
	int compare(Cuboid & c);
};
#endif // !CUBOID_H_

//Cuboid.cpp

#include "pch.h"
#include "Cuboid.h"


Cuboid::Cuboid(double length, double width, double height)
{
	length_ = length;
	width_ = width;
	height_ = height;
}

Cuboid::Cuboid()
{
}


Cuboid::~Cuboid()
{
}

int Cuboid::compare(Cuboid & c)
{
	if (this->volume() > c.volume())
	{
		return 0;
	}
	else if (this->volume() == c.volume())
	{
		return 1;
	}
	else
	{
		return 2;
	}
}

//19-this指针.cpp

#include "pch.h"
#include "Cuboid.h"
#include <iostream>

using namespace std;

int main()
{
	Cuboid c1(20, 10.5, 11.5);
	Cuboid c2(11.5, 22, 9.5);
	int res = c1.compare(c2);
	if (res == 0)
	{
		cout << "第一个长方体的体积大于第二个长方体的体积" << endl;
	}
	else if (res == 1)
	{
		cout << "两个长方体的体积相等" << endl;
	}
	else
	{
		cout << "第一个长方体的体积小于第二个长方体的体积" << endl;
	}
	return 0;
}

 

[展开全文]

授课教师

SIKI学院老师

课程特色

下载资料(1)
视频(43)

学员动态