C++中指向类的指针
编程语言
2019-04-01 10:30:52
阅读次数: 0
1.指向类的指针
- 一个指向C++类的指针与指向结构体的指针类似,访问指向类的指针的成员,需要使用成员访问运算符->,就像访问指向结构体的指针一样。与所有的指针一样,必须在使用指针之前,对指针进行初始化。
- 实例如下:
#include "iostream"
using namespace std;
class Box{
public:
Box(double l, double w, double h): length(l), width(w), height(h){
cout << "Box类的构造函数在这!\n";
}
double Volume(){
return length * width *height;
}
private:
double length;
double width;
double height;
};
int main(){
Box box1(3.3, 4.3, 2.1);
Box box2(4.8, 1.2, 3.9);
Box *boxptr; // 定义一个指向Box类的指针变量boxptr
// 指针变量的初始化
boxptr = &box1; // 保存第一个对象的地址
cout << "Box1的体积是: " << boxptr->Volume() << endl;
boxptr = &box2;
cout << "Box2的体积是: " << boxptr->Volume() << endl;
return 0;
}
转载自blog.csdn.net/cdlwhm1217096231/article/details/88942840