C++ const问题

扫码查看

如果我这样做:

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

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

编译器不会提示Foo::foo的签名不匹配。但是,如果我有:
void foo(const bar*); //In header
void Foo::foo(bar*) {} //In cpp

该代码将无法编译。

到底是怎么回事?
我正在使用gcc 4.1.x

最佳答案

第一个示例中的const关键字是没有意义的。您是在说您不打算更改指针。但是,指针是按值传递的,因此无论是否更改它都没有关系。它不会影响调用者。同样,您也可以这样做:

// In header
class Foo {
void foo( int b );
};

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

您甚至可以这样做:
// In header
class Foo {
void foo( const int b );
};

// In cpp
void Foo::foo( int b ) {
//Stuff
}

由于int是通过值传递的,因此常量性无关紧要。

在第二个示例中,您说您的函数采用了指向一种类型的指针,但随后将其实现为采用了指向另一种类型的指针,因此它失败了。

10-01 22:38
查看更多