一个指向 C++ 类的指针与指向结构的指针类似,访问指向类的指针的成员,需要使用成员访问运算符 ->,就像访问指向结构的指针一样。与所有的指针一样,您必须在使用指针之前,对指针进行初始化。
在 C++ 中,指向类的指针指向一个类的对象,与普通的指针相似,指向类的指针可以用于访问对象的成员变量和成员函数。
声明和初始化指向类的指针
#include <iostream> class MyClass { public: int data; void display() { std::cout << "Data: " << data << std::endl; } }; int main() { // 创建类对象 MyClass obj; obj.data = 42; // 声明和初始化指向类的指针 MyClass *ptr = &obj; // 通过指针访问成员变量 std::cout << "Data via pointer: " << ptr->data << std::endl; // 通过指针调用成员函数 ptr->display(); return 0; }
当上面的代码被编译和执行时,它会产生下列结果:
Data via pointer: 42 Data: 42
动态分配内存
指向类的指针还可以用于动态分配内存,创建类的对象:
#include <iostream> class MyClass { public: int data; void display() { std::cout << "Data: " << data << std::endl; } }; int main() { // 动态分配内存创建类对象 MyClass *ptr = new MyClass; ptr->data = 42; // 通过指针调用成员函数 ptr->display(); // 释放动态分配的内存 delete ptr; return 0; }
Data: 42
指向类的指针作为函数参数
指向类的指针可以作为函数参数传递:
#include <iostream> class MyClass { public: int data; void display() { std::cout << "Data: " << data << std::endl; } }; // 函数接受指向类的指针作为参数 void processObject(MyClass *ptr) { ptr->display(); } int main() { MyClass obj; obj.data = 42; // 将指向类的指针传递给函数 processObject(&obj); return 0; }
实例
下面的实例有助于更好地理解指向类的指针的概念:
#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; } 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 *ptrBox; // Declare pointer to a class. // 保存第一个对象的地址 ptrBox = &Box1; // 现在尝试使用成员访问运算符来访问成员 cout << "Volume of Box1: " << ptrBox->Volume() << endl; // 保存第二个对象的地址 ptrBox = &Box2; // 现在尝试使用成员访问运算符来访问成员 cout << "Volume of Box2: " << ptrBox->Volume() << endl; return 0; }
Constructor called. Constructor called. Volume of Box1: 5.94 Volume of Box2: 102