C++ Error: passing ” “as” ” discards qualifiers

Today, I wrote a small piece of code. I thought it was correct, but after running it, it was somehow “discard qualifier”“

Here is the original program:

#include< iostream>

using namespace std;

class Date

{

int year;

public:

Date(int y):year(y){}

int get_ year()

{

return year;

}

int plus(const Date& p)

{

int total = p.get_ year()+year;

return total;

}

};

int main()

{

Date q(1000);

Date p(2000);

cout<& lt; p.plus(q);

system(“pause”);

}

Passing ` const date ‘as ` this’ argument of ` int date:: get_ What do you mean by year ()’discards qualifiers?Original const date & amp; p. The compiler decides to call const member function, that is, it can’t modify the member value of P call_ Year, just read, no modify?In principle, there is no modify, but the C + + compiler always assumes that you can modify the value. In fact, it can modify the value, so it is inconsistent with const member function. How can I change the two methods. First, remove const. Second, in get_ Add const after year

 

#include< iostream>

using namespace std;

class Date

{

int year;

public:

Date(int y):year(y){}

int get_ year()

{

return year;

}

int plus(const Date& p)const

{

int total = p.get_ year()+year;

return total;

}

};

int main()

{

Date q(1000);

Date p(2000);

cout<& lt; p.plus(q);

system(“pause”);

}

That’s right.

The above is just a little thinking for beginners, for your reference~~~

Similar Posts: