[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
类的初始化
如果类中有私有成员,那么之前的struct赋值方法是不能成功的
struct Role r{"alex",190,199};
类似于这种,这种方式不能给私有成员进行赋值
于是就有了构造函数
构造函数
在类的里面,有一个特殊的成员函数,构造函数,它在类被创建时自动调用,名字与类名相同,没有返回值,void也没有,任何类都要有构造函数。
语法
函数名 () { }
Cclass Role { int hp; 默认构造 Role() { hp=100; } 有参构造 Role(int _hp) { hp=_hp; }
Role(Role& r) { hp= r.hp; } }
如果没有给类设置构造函数,那么编译器就会默认给它一个默认构造函数,没有参数,没有返回值
Role()=default
只要我们给类定义了构造函数,默认构造函数就不会再有,如果我们一定要有一个默认的构造函数怎么办呢?1显示的指定一个默认构造函数,2。Role()=default
Role() { }; Role()=default;
default的执行效率更高,可以用的话就用它,如果默认构造里面有语句,那还是用显示指定吧
思考 这里为什么会出错
class Role { int hp; Role(); Role(int _hp=100) { hp=_hp }; } int main() { Role
r; }
因为这两个构造函数都可以不写实参
explicit关键字
class Role { public: int hp; Role(int _hp=100) { hp = _hp; }; bool
isbigger(Role r) { return r.hp > hp; } }; int main() { Role r;
std::cout<<r.isbigger(500); }
这里的isbigger的参数明明时Role类型,为什么可以输入500呢?因为输入500,调用了构造函数,将r赋值为500,即 isbigger ( Role
(500) )
被explicit修饰的构造函数会禁用这种转换,只需要在构造函数前加上explicit即可