空类占一个字节!!!
1、友元机制
- 种类:
- 友元类
- 友元函数
- 友元成员函数
- 作用:提高程序的运行效率(让类的非公有函数可以直接访问类的非公有成员,省去了函数的调用过程)
- 缺点:破坏了C++的封装性
- 注意事项:
- 单向访问(只有friend才可以访问我的变量)
- 不可以传递
- 友元成员函数:声明另外一个类中的某一个成员函数可以访问本类(所有成员函数必须在类外声明)
2、函数运算符的重载
- 类型转换运算符的重载
-
- ++i
-
- i++
-
-
- i ++ 在实现的过程中会创建一个新的临时变量存储
- ++ i 不会创建一个新的临时变量
-
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
using p_func = void(*)(void);
class Test
{
public:
int m_num;
string m_s;
char *m_ptr;
Test()
{
m_ptr = new char[100];
}
Test(int num, string s, char *ptr) : m_num(num), m_s(s)
{
int len = strlen(ptr);
this->m_ptr = new char[len + 1];
strcpy(m_ptr, ptr);
}
~Test()
{
delete[] m_ptr;
}
static void print()
{
cout << "hello world" << endl;
}
Test &operator=(const Test &other)
{
if (this != &other)
{
this->m_num = other.m_num;
this->m_s = other.m_s;
int len = strlen(other.m_ptr);
this->m_ptr = new char[len + 1];
strcpy(m_ptr, other.m_ptr);
}
return *this;
}
bool operator>(const Test &t)
{
return this->m_num > t.m_num;
}
bool operator<(const Test &t)
{
return this->m_num < t.m_num;
}
friend ostream &operator<<(ostream &out, const Test &t)
{
out << "num = " << t.m_num << endl;
out << "s = " << t.m_s << endl;
out << "ptr = " << t.m_ptr;
return out;
}
friend istream &operator>>(istream &in, Test &t)
{
in >> t.m_num;
in >> t.m_s;
in >> t.m_ptr;
return in;
}
operator int() //类型转换运算符的重载
{
return this->m_num;
}
operator char*() //类型转换运算符的重载
{
return this->m_ptr;
}
operator p_func() //类型转换运算符的重载
{
return print;
}
//i++ ,++i; //实现
//()函数运算符 -- 函数对象
};
int main()
{
string s = "hello world";
Test t1(1, s, "zhangsan");
Test t2;
t2.operator=(t1);
//cout << s << "hello" << endl;
//cout.operator<<(cout,t2);
//operator<<(cout,t2);
cout << t2 << "hello" << endl;
Test t3;
cin >> t3;
cout << t3 << endl;
if(t2 > t3)
{
cout << "t2 > t3" << endl;
}
int num = static_cast<int>(t3);
int num2 = static_cast<int>(t2);
cout << num << endl;
cout << num2 << endl;
string s2 = static_cast<string>(t3);
char *ptr = static_cast<char *>(t2);
//cout << s2 << endl;
cout << ptr << endl;
p_func f = static_cast<p_func>(t2);