C++友元类和派生类访问变量的怪异之处

有一个很蠢的问题,其实一般也不太可能这样写,不过C++Primer上讲解内容时用来举例子,突发奇想试下它们的区别,结果郁闷了...

class Quote
{
    friend class Bulk_quote;
private:
    string bookNo;
public:
    Quote() = default;
    Quote(const string &book, double sales_price) :
        bookNo(book), price(sales_price) {}
    virtual ~Quote() = default;

    virtual double net_price(size_t n) const
        {return n * price;}
    string isbn() const {return bookNo;}
    int i = 1;
protected:
    double price = 0.0;
};

class Bulk_quote
{
public:
    double test() { return price; }
};

这个报错

class Quote
{
private:
    string bookNo;
public:
    Quote() = default;
    Quote(const string &book, double sales_price) :
        bookNo(book), price(sales_price) {}
    virtual ~Quote() = default;

    virtual double net_price(size_t n) const
        {return n * price;}
    string isbn() const {return bookNo;}
    int i = 1;
protected:
    double price = 0.0;
};

class Bulk_quote : public Quote
{
public:
    double test() { return price; }
};

这个没有...

c++

1个回答

派生类是自己继承了变量price,因为自己有,所以可以访问,友元类的访问需要有实际的对象,否则无法访问

#include<iostream>
using namespace std;
class Quote
{
    friend class Bulk_quote;
private:
    string bookNo;
public:
    Quote() = default;
    Quote(const string& book, double sales_price) :
        bookNo(book), price(sales_price) {}
    virtual ~Quote() = default;

    virtual double net_price(size_t n) const
    {
        return n * price;
    }
    string isbn() const { return bookNo; }
    int i = 1;
protected:
    double price = 0.0;
};

class Bulk_quote
{
public:
    double test(Quote s) { return s.price; }
};
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问