const成员
1.const数据成员
(1)const类型变量为只读,不可修改
(2)采用初始化参数列表方式初始化
2.const成员函数
(1)写在函数后
(2)常成员函数不能够修改数据成员,只能读取
(3)常成员函数可以和普通成员函数同时存在
①普通对象优先调用普通成员函数
②普通对象在无普通成员函数时,可以调用常成员函数
3.const对象(只能调用常成员函数)
#include <iostream>
#include <string>
using namespace std;
class Boy
{
public:
Boy(string name,int age) :name(name),age(age){}
void print()
{
cout << name << "\t" << age << endl;
}
void print()const
{
cout << name << "\t" << age << endl;
cout << "常成员函数" << endl;
}
protected:
string name;
const int age; //const 数据成员
};
int main()
{
Boy boy("姓名",1);
boy.print();
const Boy boy1("常对象", 1);
boy1.print();
return 0;
}
static成员
注:
①static成员不属于对象,属于类,调用可以不需要对象(所有对象共有)
②static成员依旧受权限限定
1.static数据成员
(1)必须在类外初始化,不需要static修饰,但需要类名限定
(2)不可以在类中初始化,不能采用初始化参数列表初始化
2.static成员函数
(1)static写在函数前
(2)调用非静态成员必须要指定对象
3.static对象:最后释放
#include <iostream>
#include <string>
using namespace std;
class Boy
{
public:
Boy(string name=" ") :name(name)
{
num++;
}
static void print();
static void printdata(Boy& boy)
{
cout << boy.name << "\t" << num << endl;
}
static int num;
protected:
string name;
};
//类外初始化不需要static修饰,但需要类名限定
int Boy::num = 0;
void Boy::print()
{
cout << "静态成员函数" << endl;
}
int main()
{
cout << Boy::num << endl;//访问不需要对象
Boy boy1("姓名");//静态数据成员(共有)
cout << boy1.num << endl;//打印1
Boy array[3];
Boy* p = new Boy("姓名");
cout << p->num << endl;//打印5
delete p;
p = nullptr;
Boy::print();
Boy::printdata(boy1);
return 0;
}
友元
注:友元只是提供一个场所,赋予对象具有打破类的权限限定
1.友元函数
(1)用friend描述的关系
(2)普通友元函数
#include <iostream>
#include <string>
using namespace std;
class Boy
{
public:
Boy(string name, int num) :name(name), num(num){}
void print()
{
cout << name << "\t" << num << endl;
}
friend void printdata();
protected:
string name;
private:
friend void printdata1(Boy& boy);
int num;
};
void printdata()
{
//提供场所,无视权限
Boy boy("姓名", 0);
cout << boy.name << "\t" << boy.num << endl;
}
void printdata1(Boy& boy)
{
cout << boy.name << "\t" << boy.num << endl;
}
int main()
{
Boy boy("姓名", 1);
boy.print();
printdata1(boy);
printdata();
return 0;
}
(3)以另一个类的成员函数充当友元函数
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
void printB();//声明函数
protected:
string name = "ABCD";
};
class B
{
public:
friend void A::printB();//声明为友元函数
protected:
string name = "abcd";
};
void A::printB()//函数实现
{
B b;
cout << b.name << endl;
}
int main()
{
A a;
a.printB();
return 0;
}
2.友元类
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A(string name) :name(name){}
friend class B;
protected:
string name = "A";
};
class B
{
public:
void print()
{
A a("a");
cout << a.name << endl;
}
void printA(A& a)
{
cout << a.name << endl;
}
protected:
string name = "B";
};
int main()
{
A a("abcd");
B b;
b.print();
b.printA(a);
return 0;
}
this指针与explicit
1.修饰构造函数,不让隐式转换构造
2.this指针
(1)避免形参名和数据名同名,通指对象的地址
(2)充当函数返回值,返回对象自身(*this)
(3)静态成员函数中不能使用this指针