简体   繁体   中英

Const changing variable values

I have a virtual get method that looks like this in the super class:

virtual double getPortagem() const;    
double via_Ligacao::getPortagem() const
 {
    return 0;
 }

And in their "child":

double getPortagem();
double auto_Estrada::getPortagem()
{
    return portagem;
}

The thing that is bugging me is if I declare the child method as non const the results will be accoding to the values inserted but if I declare as a const method it will return me a memory position. Could you guys explain me this, please?

函数重写没有完成,因为你在子类中创建一个新函数,通过声明非const函数,它与超类中的函数没有任何匹配。

In C++11 you can use the keyword override to ensure that an intended override really is an override:

double auto_Estrada::getPortagem() override
{
    return portagem;
}

Then you get a compilation error if it isn't an override, which this non- const function isn't (since it differs in const -ness from the base class method of the same name).

Instead of overriding the base class function this function shadows the base class function, so that if you call o.getPortagem() where o is const and of class auto_Estrada , the compiler won't find the base class const function, and complain.

In C++03 about the best you could do was to statically assert that the same named base class function could be called with the same arguments (it helped but wasn't guaranteed). Note that C++03 didn't have a static_assert . The usual way to do C++03 static asserts was via a typedef of an array, with negative size where you wanted a compile time error.


Regarding terminology,

what you call a "child class" is a derived class (C++ terminology) or subclass (more general computer science terminology, I believe originally from Smalltalk),

what you call "memory position" appears to be arbitrary bits in an uninitialized variable, interpreted as a floating point value, which is called an indeterminate value .

It's formally Undefined Behavior to use an indeterminate value, so anything can happen.

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