Posted on 2008-07-17 17:56
softgamer 阅读(243)
评论(0) 编辑 收藏 引用 所属分类:
学习日志
在这里不说类的概念了,大家都清楚,只是说说关于类的注意事项
1.类的数据成员不能在类体中声明时初始化,而还是要用类的构造函数初始化,或者用set 函数赋值
2.析构函数能不能被重载?不能,因为析构函数不能带参数,所以不能重载
3.外部访问private类成员只能用public类接口通过public成员函数访问。尽量使所有类的成员保持private
实现规范是 1.提供public函数,2.设置private数据成员的值,3.获得private数据成员的值
4.提供public成员set,get函数是重要的,它可以让用户读写private成员
5.重点来了
返回对private数据成员的引用,是非常危险的!!!!
如
#pragma once
class CDay
{
public:
CDay( int );
virtual ~CDay(void);
void setDay( int day );
int getDay();
int &badsetDay( int day ); // DANGEROUS
private:
int Day;
};
#include "StdAfx.h"
#include "Day.h"
CDay::CDay( int day )
{
setDay( day );
}
CDay::~CDay(void)
{
}
void CDay::setDay( int day )
{
Day = day;
}
int CDay::getDay()
{
return Day;
}
//Returning a ref to private data member
int &CDay::badsetDay( int day )
{
Day = ( day >= 0 && day < 31 )?day:0;
return Day;
}
// test1.cpp : 定义控制台应用程序的入口点。
//
#include "iostream"
using namespace std;
using namespace std;
#include "Day.h"
int _tmain(int argc, _TCHAR* argv[])
{
CDay c( 11 );
int &Dayref = c.badsetDay( 21 );
cout << "\n Day before mod: " << Dayref;
Dayref = 41; // modied //Dangerous Function call
cout << "\n Day after mod: " << c.getDay();
//Dangerous Function call
//a ref can be used as an lvalue
c.badsetDay( 12 ) = 74;
cout << "\n\n***************************\n"
<< "badsetDay as an lvalue Day:"
<< c.getDay()
<< "\n*******************************\n" << endl;
return 0;
}
结果是:
Day before mod: 21
Day after mod: 41 //wrong Day above 31
***************************
badsetDay as an lvalue Day:74 //wrong Day above 31
*******************************