C++ const question

后端 未结 7 1581
遥遥无期
遥遥无期 2020-12-20 16:58

If I do this:

// In header 
class Foo {
void foo(bar*);
};

// In cpp
void Foo::foo(bar* const pBar) {
//Stuff
}

The compiler does not comp

7条回答
  •  一生所求
    2020-12-20 17:27

    The const keyword in the first example is meaningless. You are saying that you don't plan on changing the pointer. However, the pointer was passed by value and so it dos not matter if you change it or not; it will not effect the caller. Similarly, you could also do this:

    // In header 
    class Foo {
    void foo( int b );
    };
    
    // In cpp
    void Foo::foo( const int b ) {
    //Stuff
    }
    

    You can even do this:

    // In header 
    class Foo {
    void foo( const int b );
    };
    
    // In cpp
    void Foo::foo( int b ) {
    //Stuff
    }
    

    Since the int is passed by value, the constness does not matter.

    In the second example you are saying that your function takes a pointer to one type, but then implement it as taking a pointer to another type, therefore it fails.

提交回复
热议问题