《C++ 大学教程》10.2 const对象和const成员函数

1、程序员使用关键字const来指定对象是不可修改的,这样任何试图修改对象的操作都将导致编译错误。
2、对于const对象,C++ 编译器不允许进行成员函数的调用,除非成员函数本身也声明为const(const对象调用非const成员函数将导致编译错误,const对象只能调用const成员函数
但是在构造函数中调用非const成员函数来初始化const对象是允许的。
3、要将函数指定为const,既要在其函数原型中指定,也要在其定义中指定。
4、可以对const成员函数进行非const版本的重载。
5、因构造函数和析构函数都会修改对象,所以试图将构造函数和析构函数修改为const是一个错误。
6、所有的数据成员均可以用成员初始化器形式进行初始化,但是const数据成员和引用的数据成员必须使用成员初始化器进行初始化。(成员对象也必须以这种方法进行初始化)
**常量数据成员(const对象和const变量)和声明为引用的数据成员必须采用成员初始化器语法形式进行初始化,**在构造函数中为这些类型数据赋值是不允许的。
7、类中的静态变量和常量,都应该在类定义之外加以定义,但C++ 标准规定了一个例外:类的静态常量如果具有整数类型或枚举类型,那么可以直接在类定义中为它指定常量值。
Eg. Static const int b = 10;

//Time.h
#ifndef TIME_H
#define TIME_H

class Time
{
public:
	Time( int = 0, int = 0, int = 0 );
	//~Time();

	void setTime( int, int, int );
	void setHour( int );
	void setMinute( int );
	void setSecond( int );

	int getHour() const;
	int getMinute() const;
	int getSecond() const;

	void printUniversal() const;
	void printStandard();

private:
	int hour;
	int minute;
	int second;

};


#endif
//Time.cpp
#include <iostream>
#include <iomanip>
#include "Time.h"
using namespace std;

Time::Time( int h, int m, int s )
{
	setTime( h, m, s );
}
void Time::setTime( int h, int m, int s )
{
	setHour( h );
	setMinute( m );
	setSecond( s );
}

void Time::setHour( int h )
{
	hour = ( h >= 0 && h < 24 ) ? h : 0;
}
void Time::setMinute( int m )
{
	minute = ( m >= 0 && m < 60 ) ? m : 0;
}
void Time::setSecond( int s )
{
	second = ( s >= 0 && s < 60 ) ? s : 0;
}

int Time::getHour() const 
{
	return hour;
}
int Time::getMinute() const
{
	return minute;
}
int Time::getSecond() const
{
	return second;
}

void Time::printUniversal() const
{
	cout << setfill('0') << setw( 2 ) << hour << ":"
		<< setw( 2 ) << minute << ":"
		<< setw( 2 ) << second << endl;
}

void Time::printStandard()
{
	cout << ((hour == 0 || hour == 12) ? 12 : hour % 12 ) << ":"
		<< setfill('0') << setw( 2 ) << minute << ":"
		<< setw( 2 ) << second << ( hour < 12 ? "AM" : "PM");
}


//main.cpp
#include <iostream>
#include "Time.h"

int main()
{
	Time wakeUp( 6, 45, 0 );
	const Time noon( 12, 0, 0 );

	wakeUp.setHour( 18 );
	//noon.setHour( 12 );//常量对象调用非常成员函数

	wakeUp.getHour();

	noon.getMinute();
	noon.printUniversal();

	//noon.printStandard();//常量对象调用非常成员函数
}
发布了11 篇原创文章 · 获赞 7 · 访问量 5248

猜你喜欢

转载自blog.csdn.net/qq_35591140/article/details/105740845