通过对象可以访问public属性的成员变量或成员函数。访问可以通过成员选择符“.”或指针操作符“->”来完成。
#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;
}