1.const成员函数
const修饰成员函数,即在成员函数后面加上const修饰符,保证该成员函数的对象在该函数内不被改变;
class Date
{
public:
void show() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
在编译器内会优化为:
class Date
{
public:
void show(const Date* this)
{
cout << this->_year << "-" <<this-> _month
<< "-" << this->_day << endl;
}
private:
int _year;
int _month;
int _day;
};
const修饰权限只能缩小,不能放大;
const修饰的对象不能调用非const修饰的函数,只能调用const修饰的函数;
非const修饰的对象既可以调用非const修饰的函数,又能调用const修饰的函数;
const修饰的函数不能调用非const修饰的函数,只能调用const修饰的函数;
非const修饰的函数既可以调用非const修饰的函数,又能调用const修饰的函数;
#include<iostream>
#include<Windows.h>
using namespace std;
class Date
{
public:
void Display1()
{
cout << "Display ()" << endl;
cout << "year:" << _year << endl;
cout << "month:" << _month << endl;
cout << "day:" << _day << endl << endl;
}
void Display2() const
{
cout << "Display () const" << endl;
cout << "year:" << _year << endl;
cout << "month:" << _month << endl;
cout << "day:" << _day << endl << endl;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
void Test()
{
Date d1;
d1.Display1();//合法
const Date d2;
d2.Display2();// 合法
d1.Display2();//合法
d2.Display1();//不合法
}
int main()
{
Test();
system("pause");
return 0;
}
2.内联函数
以inline修饰的函数叫做内联函数,编译时C++编译器会调用内联函数的地方展开,没有函数压栈的开销,内联函数提升程序运行的效率。
内联函数的使用注意问题:
(1)内联函数不适用于很长的代码或具有递归和循环的代码;
(2)内联函数关键字必须要和函数的定义放在一起才能生效,仅放在函数的声明部分是没用的;
(3)定义在类内的成员函数默认定义为内联函数。
(4)定义为内联函数只是对编译器的一种建议,具体执行情况视编译器的优化而定;
内联和宏的共同点与不同点:
3.友元
在C++中友元函数允许在类外访问该类中的任何成员,就象成员函数一样,友元函数用关键字friend说明;
友元分为友元函数和友元类:
(1)友元函数
class Time
{
// Date是Time 的友元类,所以 Date可以访问Time的所有成员。
friend class Date;
private:
int _hour;
int _minute;
int _second;
};
class Date
{
public:
void Display()
{
cout << "year:" << _year << endl;
cout << "month:" << _month << endl;
cout << "day:" << _day << endl;
// 定义为友元类后,可以访问Time类对象的所有成员
cout << "hour:" << _t._hour << endl;
cout << "minute:" << _t._minute << endl;
cout << "second:" << _t._second << endl << endl;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
Time _t;
};
void Test()
{
Date d1;
d1.Display();
}
(2)友元类
class Date
{
friend void Display( const Date & d);
private :
int _year ; // 年
int _month ; // 月
int _day ; // 日
};
void Display (const Date& d)
{
cout<<"year:" <<d. _year<< endl ;
cout<<"month:" <<d. _month<< endl ;
cout<<"day:" <<d. _day<< endl ;
}
void Test ()
{
Date d1 ;
Display(d1 );
}
友元使用的问题:
(1)友元函数不是类的成员函数。
(2)友元函数可以通过对象访问所有成员,私有和保护成员也一样。
(3)整个类可以是另一个类的友元。友元类的每个成员函数都是另一个类的 友元函数,都可访问另一个类中的保护或私有数据成员。
(4)友元在一定程度上破坏C++的封装性;
4.static成员
static可修饰成员变量,也可修饰成员函数;
5.N中构造拷贝构造的优化
Test1中调用了_1__次AA的拷贝构造函数,_1__次AA的赋值运算符函数的重载。
Test2中调用了_2__次AA的拷贝构造函数,_0__次AA的赋值运算符函数的重载。
Test3中调用了_3__次AA的拷贝构造函数,_0__次AA的赋值运算符函数的重载。
class AA
{};
AA f (AA a)
{
return a ;
}
void Test1 ()
{
AA a1 ;
a1 = f(a1);
}
void Test2 ()
{
AA a1 ;
AA a2 = f(a1);
}
void Test3 ()
{
AA a1 ;
AA a2 = f(f(a1));
}