简体   繁体   中英

C++ can't access public members

I'm a new C++ learner. Given the following code in C++, why I can't access this.init() in a function even though it's public?

class Complex {

private:
    double re, im;
public:
    void init(double x, double y);
    void add(Complex c);
    double abs(double x)const;
    static int Num;
    Complex(double x,double y=0)
    {
        re=x;
        im=y;
    }
};

double Complex::abs(double x) const {
    //Why I can't access this.init?
    Num++;
    return 0;
}

Your abs function is marked const :

double Complex::abs(double x) const;

and so when is called, the caller object is guarantee not to change, and so if you try to change the value of Num compiler won't let you do it, because you are violating the constness of the objects

You can't call non-const functions from const functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM