一、const成员函数
定义成员函数时通过如下声明来确保类方法不会修改所访问的数据:
在写函数声明的时候,后面加上const修饰符;在定义函数本体时,后面加上const修饰符。
void function(int num) const;
void function(int num) const
{
statement;
}
二、this指针
所有的类成员函数都包括一个隐含参数,this指针,这是一个指向这个类型的指针;虽然在函数声明和函数定义中并没有显示这个参数,但这个参数是的的确确存在的,编写函数的时候可以直接调用!
this指针会指向对象自身,所以如果这个对象有一个int型成员变量a,可以通过如下方式访问变量a
this->a
所以看下面这一段程序
#include <iostream>
#include <string>
using namespace std;
class Vehicle
{
private:
string name;
string color;
int price;
int type;
public:
Vehicle();
Vehicle(string p_name,string p_color,int p_price,int p_type);
};
Vehicle::Vehicle():name("no name"),color("no color"),price(0),type(0)
{
}
Vehicle::Vehicle(string p_name,string p_color,int p_price,int p_type)
{
name=p_name;
color=p_color;
price=p_price;
type=p_type;
}
int main(void)
{
Vehicle car1("BMW M3","Blue",850000,1);
}
在构造函数Vehicle中,name=p_name等价于this->name=p_name,依次类推,所以Vehicle可以如下定义:
Vehicle::Vehicle(string p_name,string p_color,int p_price,int p_type)
{
this->name=p_name;
this->color=p_color;
this->price=p_price;
this->type=p_type;
}
事实上,name在函数定义中是this->name的缩写,类方法是依靠this指针访问成员对象的!
三、类似结构体的->
注意到,this指针后使用了->运算符,因为this->name可以被理解为(*this).name,这和结构体中的定义是一模一样的!
不光this指针,任何类型为指向某种类型的指针都可以使用该运算符号,下面是示例:
#include <iostream>
#include <string>
using namespace std;
class Vehicle
{
private:
string name;
string color;
int price;
int type;
public:
Vehicle();
Vehicle(string p_name,string p_color,int p_price,int p_type);
void changeprice(int newprice)
{
price=newprice;
}
};
Vehicle::Vehicle(string p_name,string p_color,int p_price,int p_type)
{
this->name=p_name;
this->color=p_color;
this->price=p_price;
this->type=p_type;
}
int main(void)
{
Vehicle* car2=new Vehicle("BMW M4","Yellow",1200000,2);
car2->changeprice(1000000);
}
car2->changeprice(1000000);
这一语句即是->运算符号的实例,说明 指向对象的指针->成员函数 的方式是可以被使用的。
注意,对于定义在堆上的对象,如果对象的构造函数需要带参数,则在new运算符后加上参数:
Vehicle* car2=new Vehicle("BMW M4","Yellow",1200000,2);
很有意思!