類指針學習1.1|C++類指針例子
#include <iostream>
?
using namespace std;
class Box
{
? ?public:
? ? ? // 構造函數(shù)定義
? ? ? 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;
? ? ? }
? ?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
? ?Box Box3(3, 7.0, 1.0); ? ?// Declare box2
? ?Box *ptrBox; ? ? ? ? ? ? ? ?// Declare pointer to a class.
? ?// 保存第一個對象的地址
? ?ptrBox = &Box1;
? ?// 現(xiàn)在嘗試使用成員訪問運算符來訪問成員
? ?cout << "Volume of Box1: " << ptrBox->Volume() << endl;
? ?// 保存第二個對象的地址
? ?ptrBox = &Box2;
? ?// 現(xiàn)在嘗試使用成員訪問運算符來訪問成員
? ?cout << "Volume of Box2: " << ptrBox->Volume() << endl;
? ?
? ?// 保存第三個對象的地址
? ?ptrBox = &Box3;
? ?// 現(xiàn)在嘗試使用成員訪問運算符來訪問成員
? ?cout << "Volume of Box3: " << ptrBox->Volume() << endl;
??
? ?return 0;
}
輸出結果:
Constructor called.
Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102
Volume of Box3: 21
=reference=
[1]https://www.runoob.com/cplusplus/cpp-pointer-to-class.html