特殊成员函数

来源:互联网 发布:spark hbase性能优化 编辑:程序博客网 时间:2024/06/10 18:46

特殊函数成员

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
原创粉丝点击