C++ primer 第十六章 继承构造函数

来源:互联网 发布:微博淘宝客优惠券 编辑:程序博客网 时间:2024/05/22 00:25

异常处理

直接上代码:

try{pInt.~Handle();cout << ++i<< "\t" << *pInt << "\t" << *pInt2 << "\t" << *pInt3 << ends; /*执行了前面的++操作,但是出现异常,异常销毁只会析构和处理变量,不会回滚操作*/}catch (runtime_error e){cerr << i << "\t"<< e.what() << endl;}


#pragma once#include "Item_base.hpp"#include "Handle.hpp"class Sales_item{public:Sales_item() :h() {}Sales_item(const Item_base & item) :h(item.clone()){}Item_base & operator *(){return *h;}Item_base * operator &(){return h.operator->();}const Item_base & operator *() const{return  *h;}const Item_base * operator &() const{return h.operator->();}private:Handle<Item_base> h;};

使用原生字符串常量(raw string literal)

之前我也遇到coso2dx在VS上无法打印中文字符调试的问题,而C++标准一出,增加Unicode的标准,蛮好的。另一方面,由于继承的父类构造函数将导致新的风险,即增加了构造函数,可以显示的把某些构造函数 = deleted 掉,例如: 
Disc_item() = deleted;
源码如下:
class Disc_item : public Item_base{using Item_base::Item_base;/* 试试继承构造函数,但发现如果基类的默认值不是很有效果的情况下, * 继承构造函数并不能有效减少代码编写量; * 另外继承构造函数同时增加了构造函数重载, * 即会有基类构造函数接口去允许生成派生类对象,而派生类对象新增部分的初始化时未知(若无默认快速初始化) */public:Disc_item(const std::string & book = "", double sales_price = 0.0, std::size_t qty = 0, double discount = 0.0):Item_base(book, sales_price), min_qty(qty), disc_rate(discount){std::cout << R"(Disc_item 构造函数)" << std::endl;}virtual ~Disc_item(){std::cout << R"(Disc_item 析构函数)" << std::endl;}virtual double net_price(std::size_t n) const = 0;Disc_item(const Disc_item & other) :Item_base(other), disc_rate(other.disc_rate), min_qty(other.min_qty){std::cout << R"(Disc_item 复制构造函数)" << std::endl;}Disc_item & operator =(const Disc_item & other){if (this != &other){Item_base::operator=(other); //切片式初始化基类部分}min_qty = other.min_qty;disc_rate = other.disc_rate;std::cout << R"(Disc_item =赋值函数)" << std::endl;return *this;}



但是问题还是没解决,继承的构造函数没有减少代码量书写,还是无法完美的实现初始化,只能说在基类有合成的默认构造函数才适合使用或者说POD形式父类数据初始化直接继承构造函数即可。
下载代码VS2013
0 0