C++类的指针

来源:互联网 发布:js 严格模式 eval 编辑:程序博客网 时间:2024/05/17 03:06

一个指向 C++ 类的指针与指向结构的指针类似,访问指向类的指针的成员,需要使用成员访问运算符 ->,就像访问指向结构的指针一样。与所有的指针一样,您必须在使用指针之前,对指针进行初始化。

下面的实例有助于更好地理解指向类的指针的概念:

#include<iostream>using namespace std;class xc{    private:        double length;        double width;        double height;    public:        void set(double len,double wid,double hei);            double vol(void);        };void xc::set(double len,double wid,double hei){            length=len;            width=wid;            height=hei;}double xc::vol(void){    return length*width*height;}int main(){    xc sw1;    xc sw2;    sw1.set(1.5,2.5,3.5);    sw2.set(4.5,5.5,6.5);    xc *pxc;    pxc=&sw1;    cout<<"vol for sw1:"<<pxc->vol()<<endl;    pxc=&sw2;    cout<<"vol for sw2:"<<pxc->vol()<<endl;    return 0;}


0 0
原创粉丝点击