How to call constructor and variables from another class?

好久不见. 提交于 2019-12-25 18:29:29

问题


I have a main class:

class Sportist{
    private:
        string ime;
        int godina_na_ragjanje;
        int godisna_zarabotuvacka_EUR;
    public:
        Sportist(string i, int g_n_r, int g_z_EUR){
            ime = i;
            godina_na_ragjanje = g_n_r;
            godisna_zarabotuvacka_EUR = g_z_EUR;
        }
};

And now I have a new class like this:

class Fudbaler:public Sportist{
    private:
        int broj_na_odigrani_natprevari;
        int danocna_stapka;
    public:
        Fudbaler(string ime, int godina, int zarabotuvacka, int b, int d){
            :Sportist(ime, godina, zarabotuvacka)
            broj_na_odigrani_natprevari = b;
            danocna_stapka = d;
        }
        float danok(){
            return godisna_zarabotuvacka_EUR * danocna_stapka;
        }
        friend ostream& operator<<(ostream &os, Fudbaler F){
            return os << "Ime: " << ime << endl
                      << "Godina na raganje: " << godina_na_ragjanje << endl
                      << "Godisna zarabotuvacka(EUR): " << godisna_zarabotuvacka_EUR << endl
                      << "Danok sto treba da plati: " << danok();
        }
};

I want to call the constructor from the first class in the second class, but I get errors that I haven't provided arguments which I do.. and also, I want to know how to access the private elements from the first class in the second, because it's taken as 'public', so how can I use them in my functions, like danok().

Errors while calling the constructor:

no matching function for call to 'Sportist::Sportist()'

candidates are:

Sportist::Sportist(std::string, int, int)

candidate expects 3 arguments, 0 provided

Error while calling variables using public method:

'int Sportist::godisna_zarabotuvacka_EUR' is private


回答1:


You do not initialize Sportist before you enter your Fudbaler constructor function body. Therefore the Compiler tries to use a default constructur of Sportist which does not exists. You Need to initialize Sportist before entering the Fudbaler constructor body.

Initializers are appended after the closing parenthesis before the function body in curly brackets:

    Fudbaler(string ime, int godina, int zarabotuvacka, int b, int d)
       : Sportist(ime, godina, zarabotuvacka), 
        broj_na_odigrani_natprevari(b), 
        danocna_stapka(d)
    {
    }

Private variables are private and cannot be accessed in child classes. If you want to Access the Sportist members in Fudbaler member function you need to declare them protected (only accessible in this class and child classes) or public (generally accessible).



来源:https://stackoverflow.com/questions/23720882/how-to-call-constructor-and-variables-from-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!