-1

I have this class:

class BankAccount{
    private:
        char* ownerName;
        char IBAN[14];
        double balance;
}

And I have this function:

char* BankAccount::getIban(){
    return this->IBAN;
}

That one is valid but I wonder why I can't define getIban() like this, because I want to make sure that IBAN can't be changed :

char* BankAccount::getIban()const{
    return this->IBAN;
}

It says return value does not match the function type.

4

3 回答 3

8

Inside a const function all of the members behave as if they were const, in your case the member IBAN is equivalent to const char IBAN[14]. You cannot get a non-const char* to refer to a const array, and thus the error. You probably want to do:

const char* BankAccount::getIban() const {
    return IBAN;
}
于 2013-10-08T20:27:23.227 回答
0

you have to include const in the function declaration in the header

于 2013-10-08T20:26:46.000 回答
-1

If you declare a method const when defining it the compiler WONT LET YOU potentially ruin that const-ness by passing pointers to const stuff outside where they're not const.

The error is that. You need to return a const char*, that way the compiler knows when you use that function the resulting type is a const char* <-- you can look but not touch, so the IBAN value stays const.

If you make the const method return a const char* (return IBAN) it'll be fine, because when you use that method C++ wont let you change what the result of calling it points to.

于 2013-10-08T20:28:51.127 回答