zoukankan      html  css  js  c++  java
  • protected访问标号的一个生僻

        《c++ primer》15.2.2节中有这样一段话:
         派生类只能通过派生类对象访问其基类的protected成员,派生类对其基类类型对象的protected成员没有特殊权限。

              例子:Item_base是Bulk_item的基类,Bulk_item定义了一个成员方法,接受一个Bulk_item对象的引用,和一个Item_base类型对象的引用,该函数可以访问自己对象的protected成员和Bulk_item形参的protected成员,但是,它没有Item_base类型形参的protected成员的访问权限。


    代码验证:

    Item_base.h:

    #ifndef ITEM_BASE_H_INCLUDED
    #define ITEM_BASE_H_INCLUDED
    
    #include <string>
    using std::string;
    
    class Item_base
    {
    public:
        Item_base(const string & sIsbn = "", double dPrice = 0.0);
        virtual ~Item_base();
    
        virtual string book() const;
        virtual double net_price(unsigned uNumber) const;
    
    protected:
        double m_dPrice;
    
    private:
        string m_sISBN;
    };
    
    #endif // ITEM_BASE_H_INCLUDED
    
    Item_base.cpp:
    #include "Item_base.h"
    
    Item_base::Item_base(const string & sIsbn, double dPrice)
        :m_sISBN(sIsbn), m_dPrice(dPrice)
    {
    
    }
    
    Item_base::~Item_base()
    {
    
    }
    
    string Item_base::book() const
    {
        return m_sISBN;
    }
    
    double Item_base::net_price(unsigned uNumber) const
    {
        return uNumber * m_dPrice;
    }
    

    Bulk_item.h:

    #ifndef BULK_ITEM_H_INCLUDED
    #define BULK_ITEM_H_INCLUDED
    
    #include "Item_base.h"
    
    class Bulk_item : public Item_base
    {
    public:
        Bulk_item(const string& sIsbn = "", double price = 0.0);
        void memfcn(const Bulk_item & d, const Item_base & b);
    };
    
    
    #endif // BULK_ITEM_H_INCLUDED
    

    Bulk_item.cpp:

    #include "Bulk_item.h"
    #include <iostream>
    using namespace std;
    
    Bulk_item::Bulk_item(const string& sIsbn, double price)
            :Item_base(sIsbn, price)
    {
    
    }
    
    void Bulk_item::memfcn(const Bulk_item & d, const Item_base & b)
    {
        cout << "Bulk_item m_dPrice" << d.m_dPrice << endl;
        cout << "Item_base m_dPrice" << b.m_dPrice << endl; //这行导致编译失败,没有访问权限
        cout << "m_dPrice" << m_dPrice << endl;
    }
    


  • 相关阅读:
    [C++] static member variable and static const member variable
    [C++] const inside class VS const outside class
    [C++] OOP
    [C++] Function Template
    [C++] right value reference
    [C++] advanced reference
    [C++] const and char*
    [C++] c Struct VS c++ Struct
    [C++] decltype(auto) C++ 11 feature
    easyui-validatebox 的简单长度验证
  • 原文地址:https://www.cnblogs.com/yeta/p/2819759.html
Copyright © 2011-2022 走看看