c++学习笔记
封装和继承是为了实现代码的重用,
而多态是为了实现接口的重用。
sizeof(class)
对类sizeof是求类成员对其之后加虚函数表头之和
若是继承类虚函数只做一张表 也就是只有一个表头
操作符重载代码示例
#include<iostream>
using namespace std;
class Point
{
private:
int x;
public:
Point(int x1)
{ x=x1;}
Point(Point& p)
{ x=p.x;}
const Point operator+(const Point& p);//使用成员函数重载加号运算符
friend const Point operator-(const Point& p1,const Point& p2);//使用友元函数重载减号运算符
};
const Point Point::operator+(const Point& p)
{
return Point(x+p.x);
}
Point const operator-(const Point& p1,const Point& p2)
{
return Point(p1.x-p2.x);
}
int main()
{
return 0;
}
继承的代码示例
//例子
#include <iostream>
using namespace std;
#include <string>
class Animal{
string name;
public:
virtual void eat()=0;//一定不会被执行,纯虚函数
virtual void sleep(){
cout << "动物休息" << endl;
}
virtual void shout(){
cout << "动物叫" << endl;
}
};//注意分号
class Cat : public Animal{
public:
virtual /* virtual 可写可不写 */ void eat(){
cout << "猫写猫粮" << endl;
}
void sleep(){
cout << "猫睡觉" << endl;
}
void shout(){
cout << "猫喵喵叫" << endl;
}
};//注意分号
class Dog : public Animal{
public :
void eat(){
cout << "狗吃骨头" << endl;
}
void sleep(){
cout << "狗在睡觉" << endl;
}
void shout(){
cout << "我叫旺财" << endl;
}
};//分号不能少
class JiaFei : public Cat{
public :
void eat(){
cout << "加非猫爱吃意大利面" << endl;
}
void sleep(){
cout << "加非猫睡在沙发上" << endl;
}
void shout(){
cout << "加非猫说下午好" << endl;
}
}; // 分号
class Player{
string name;
public :
Player( string n ) : name(n){}
void play( Animal* p/*指针*/ ){
p->eat();
p->sleep();
p->shout();
}
void play( Animal& p /*引用*/){
p.eat();
p.sleep();
p.shout();
}
};// 分号
typedef void (*fun)(void);
int main()
{
//cout << sizeof(Animal) << endl; //输出8
Cat c;
Dog d;
JiaFei j;
Player p1( "小小" );
Player p2( "蔡依林");
p1.play(&c);
p2.play(&d);
p2.play(&j);
Cat *pc=&c;
Dog *pd=&d;
cout<<(int*)pc<<endl;
cout<<sizeof(*(int*)pc)<<endl;
cout<<sizeof(Animal)<<endl;
cout<<sizeof()<<endl;
return 0;
}
虚函数表代码示例
#include <iostream.h>
typedef void (*Fun)(void);
class Base {
public:
virtual void f(){cout<<"Base::f"<<endl;}
virtual void g(){cout<<"Base::g"<<endl;}
virtual void h(){cout<<"Base::h"<<endl;}
};
int main(){
Base b;
Fun pFun = NULL;
cout<<"虚函数表地址:"<<(int*)(&b)<<endl;
cout<<"虚函数表 — 第一个函数地址:"<<(int*)*(int*)(&b)<<endl;
pFun = (Fun)*((int*)*(int*)(&b));
pFun();
pFun = (Fun)*(1+(int*)*(int*)(&b));
pFun();
pFun = (Fun)*(2+(int*)*(int*)(&b));
pFun();
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现