2-4小时突击C++(3)
this指针
每一个对象都能通过 this指针来访问自己的地址。this指针是所有成员函数的隐含参数。友元函数没有 this 指针,因为友元不是类的成员。
例子:
#include <iostream>
using namespace std;
class Box
{
public:
// 构造函数定义
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}
输出结果:
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
指向类的指针
访问指向类的指针的成员,需要使用成员访问运算符 ->,就像访问指向结构的指针一样。
Box *ptrBox; // 申明一个指针指向类
// 保存第一个对象的地址
ptrBox = &Box1;
// 现在尝试使用成员访问运算符来访问成员
cout << "Volume of Box1: " << ptrBox->Volume() << endl;
类的静态成员
类的外部通过使用范围解析运算符 :: 来重新声明静态变量,静态函数只要使用类名加范围解析运算符 :: 就可以访问。
// 初始化类 Box 的静态成员
int Box::objectCount = 0;
// 在创建对象之后输出对象的总数
cout << "Final Stage Count: " << Box::getCount() << endl;
继承
继承允许我们依据另一个类来定义一个类。
当创建一个类时,您不需要重新编写新的数据成员和成员函数,只需指定新建的类继承了一个已有的类的成员即可。这个已有的类称为基类,新建的类称为派生类。
例如:
class Animal {
// eat() 函数
// sleep() 函数
};
//派生类
class Dog : public Animal { // bark() 函数
};
#include <iostream>
using namespace std;
// 基类
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// 派生类
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// 输出对象的面积
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
输出结果:
Total area: 35
访问控制和继承
访问 |
public |
protected |
private |
同一个类 |
yes |
yes |
yes |
派生类 |
yes |
yes |
no |
外部的类 |
yes |
no |
no |
多继承
一个子类可以有多个父类,它继承了多个父类的特性。
例子:
#include <iostream>
using namespace std;
// 基类 Shape
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// 基类 PaintCost
class PaintCost
{
public:
int getCost(int area)
{
return area * 70;
}
};
// 派生类
class Rectangle: public Shape, public PaintCost
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// 输出对象的面积
cout << "Total area: " << Rect.getArea() << endl;
// 输出总花费
cout << "Total paint cost: " << Rect.getCost(area) << endl;
return 0;
}
输出结果:
Total area: 35
Total paint cost: 2450
重载运算符和重载函数
重载声明是指一个与之前已经在该作用域内声明过的函数或方法具有相同
剩余60%内容,订阅专栏后可继续查看/也可单篇购买
本专栏主要是介绍嵌入式软件开发岗位的相关知识和学习攻略,为大家提供一份笔试与面试手册。包括有嵌入式软件开发岗位介绍与学习攻略;校园招聘和offer疑惑问题的介绍;在笔试方面,如何刷题为笔试作准备,提供往年笔试真题;在面试方面,提供相关知识的复习重点,提供面试真题。包括有:华为、蔚来、文远、大疆、三一、深信服、亚马逊、Intel、百度、科大讯飞、OPPO、京东、中兴、比特大陆|算能、美团等等
查看13道真题和解析