特殊成员函数
来源:互联网 发布: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");
}
- 特殊成员函数
- 特殊成员函数
- 特殊函数和成员
- C++:特殊成员函数
- C++—特殊成员函数
- 第17章 特殊成员函数
- C++常量成员函数特殊说明
- C++基础:常量成员函数特殊说明
- C++基础:常量成员函数特殊说明
- C++ 六种特殊成员函数
- C++类中特殊成员函数总结
- 理解特殊成员函数的生成
- 【C++程序设计】-特殊函数和成员
- 类的成员介绍(特殊成员函数)
- 类的特殊成员函数——构造函数
- 学习C++——几个特殊的成员函数
- Item 17: 理解特殊成员函数的生成规则
- Item 17: 理解特殊成员函数的生成规则
- extjs研究学习笔记《一》
- iOS推送 (百度推送)
- JAVA基础之反射(下)
- C++中L和_T()之区别
- 过滤转型
- 特殊成员函数
- 树懒_移动开学笔记_day05.2_web_tomcat
- Jquery -- 常用选择器 和 div/select/radio/checkbox的使用
- c++ 控制台版 扫雷游戏
- activity 内存释放
- 某曲线的旋转版本及其它
- HDUOJ 2502 月之数
- 如何检查 Android 应用的内存使用情况
- 跟随大神的脚步学习之开篇