特殊成员函数

特殊函数成员

1静态成员函数

静态成员函数体内不能使用非静态的成员变量和非静态的成员函数;只能调用静态成员数据和函数

因为静态属于一个类,而不是某个对象,所以没有this指针

要想访问成员变量和成员方法,需要在函数的参数中传入一个对象


#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
class computer
{
private:
 char *name;
 float price;
 static float total_price;
public:
 computer(const char *str,const float p)
 {
  name=new char[strlen(str)+1];
  strcpy(name,str);
  price=p;
  total_price+=p;
 }
 ~computer()
 {
  if(name)
  {
   delete []name;
   name=NULL;
  }
  total_price-=price;
 }
 static void print_total()
 {
  cout<<"总价:"<<total_price<<endl;
 }
 static void print(computer &com);
};

void computer::print(computer &com)
{
 cout<<"名称:"<<com.name<<endl;
 cout<<"价格:"<<com.price<<endl;
}
float computer::total_price=0;
int main()
{
 computer comp1("IBM",7000);
 computer::print(comp1);
 computer::print_total();
 computer comp2("ASUS",4999);
 computer::print(comp2);
 computer::print_total();
 comp2.~computer();
 comp2.print_total();
 system("pause");
}


2const成员函数  特点有2个:

(1)只能读取类数据成员,而不能修改之
(2)只能调用const成员函数,不能调用非const成员函数

一般的成员函数例如void Point::print()   ---->void print(Point *const this)

void Point::print()const -------->void print(const Point *const this);


#include <iostream>
#include <stdlib.h>
using namespace std;
class point
{
 int x;
 int y;
public:
 point(int xp=0,int yp=0)
 {
  x=xp;
  y=yp;
 }
 void print()const
 {
  //x=5;
  //set();
  cout<<"x="<<x<<"y="<<y<<endl;
 }
 void set()
 {

 }
};
int main()
{
 point pt;
 pt.print();
 system("pause");
}



const 对象

能作用于const对象的成员函数除了构造函数和析构函数,便只有const成员函数了

因为const对象只能被创建,撤销以及只读访问


#include <iostream>
#include <stdlib.h>
using  namespace std;
class point
{
 int x;
 int y;
public:
 point(int xp=0,int yp=0)
 {
  x=xp;
  y=yp;
 }
 ~point()
 {
  x=-1;
 }
 void setX(int xp)
 {
  x=xp;
 }
 void setY(int yp)
 {
  y=yp;
 }
 void print()const
 {
  cout<<"x="<<x<<",y="<<y<<endl;
 }
};
int main()
{
 point pt(3,4);
 pt.setX(5);
 pt.setY(6);
 pt.print();
 const point pc(1,2);
 //pc.setX(8);
 pc.~point();
 pc.print();
 system("pause");
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值