2016-03-25 30 views
0

Aşağıdaki kod var: Ben kodu çalıştırmak ve aşağıdaki çıktıyı almakC Oluşturucu ++ Veri Üyesi Adres

#include <iostream> 
#include <string> 

class Quote 
{ 
public: 
    Quote() = default; 
    Quote(const std::string &b, double p) : 
    bookNo(b), price(p) {std::cout<<"The address of p is :"<<&p<<'\n';} 
    std::string isbn() const {} 
    virtual double net_price(std::size_t n) const {return n * price;} 
    virtual ~Quote() = default; 

private: 
    std::string bookNo; 
protected: 
    double price = 0.0; 
}; 

class Bulk_quote : public Quote 
{ 
public: 
    Bulk_quote() = default; 
    Bulk_quote(const std::string& b, double p, std::size_t q, double disc) : 
    Quote(b, p), min_qty(q), discount(disc) { std::cout<<"The address of p is: " <<&p<<'\n';} 
    double net_price(std::size_t n) const override; 
private: 
    std::size_t min_qty  = 0; 
    double  discount = 0.0; 
}; 

int main() 
{ 
    Bulk_quote bq("textbook", 11.0, 5, 0.5); 
} 

,

The address of p is :0x7fff5fbff5e8 
The address of p is: 0x7fff5fbff668 
Program ended with exit code: 0 

Düşüncem olduğunu türetilmiş sınıf Yeniden kullanılmamış Temel sınıftaki kurucu. İki "p" iki sınıfta tamamen aynıdır, bu nedenle, iki "p" nin adresi aynı olmalıdır. Ancak, çıktı benim anlayışımda farklıdır.

Sorularım neden "p" nin adresi farklı? Teşekkürler

+0

Soruyla ilgisi olmayan bazı kodları atladım. – William

+1

p, bir parametre değil, bir parametredir. – kfsone

+0

"& price" yazmayı mı kastediyorsunuz? –

cevap

2

double p argümanını temel sınıf yapıcısına değer olarak iletiyorsunuz. Referans olarak iletirseniz, p adresleri aynı olacaktır. Artı, p, temel sınıfın bir üyesi değildir, bu nedenle p'un aynı adrese sahip olması için bir neden yoktur. Eğer yapıcı BulkQuote::Bulk_quote(const std::string& b, double p, std::size_t q, double disc) yılında p değiştirme endişesi olmadan Quote::Quote(const std::string &b, double p) içinde p değiştirebilir böylece

adresleri farklı.

İlgili konular