setprice; cout<<"The price of Harry is $"<getprice()<
首页 百科知识 ++成员选择符

++成员选择符

时间:2022-09-22 百科知识 版权反馈
【摘要】:[例1] 访问类的成员变量和成员函数:#includeusing namespace std;class book{public: void setprice; double getprice();private: double price;};void book::setprice{ price = a;}double book::getprice(){ return price;}int main(){ book Alice; Alice.setprice; cout<<"The price of Alice is $"<setprice; cout<<"The price of Harry is $"<getprice()<


[例1] 访问类的成员变量和成员函数:

#include<iostream>

using namespace std;


class book

{

public:

    void setprice(double a);

    double getprice();

private:

    double price;

};


void book::setprice(double a)

{

    price = a;

}


double book::getprice()

{

    return price;

}


int main()

{

    book Alice;

    Alice.setprice(29.9);

    cout<<"The price of Alice is $"<<Alice.getprice()<<endl;   

    book *Harry = new book;

    Harry->setprice(49.9);

    cout<<"The price of Harry is $"<<Harry->getprice()<<endl;

    return 0;

}

本例继续沿用上节中的book类的定义,在主函数中定义了该类的一个对象Alice,该对象通过成员选择符调用类中的setprice和getprice函数。之后又定义了一个对象指针Harry,并且进行初始化,既然是指针,当然得采用指针操作符进行函数调用了,如例中所示,Harry指针同样访问了setprice和getprice两个函数。

需要注意的是无论是成员选择符“.”还是指针操作符“->”,在类外都只能访问类中定义的public属性的成员变量或成员函数。例如在例1中,我们写出Alice.price = 29.9或者Harry->price = 49.9这样的语句,编译都是无法通过的,其原因就是上一节所说的类的信息隐藏机制。


免责声明:以上内容源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。

我要反馈

  • 藏头诗在线制作