C ++ const问题 [英] C++ const question

查看:120
本文介绍了C ++ const问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做:

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

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

编译器不会抱怨Foo :: foo的签名不匹配。但是如果我有:

The compiler does not complain that the signatures for Foo::foo do not match. However if I had:

void foo(const bar*); //In header
void Foo::foo(bar*) {} //In cpp

代码将无法编译。

发生了什么?
我使用的是gcc 4.1.x

What is going on? I'm using gcc 4.1.x

推荐答案

示例是无意义的。你说你不打算改变指针。然而,指针是通过值,所以如果你改变它不会有什么关系;它不会影响调用者。同样,你也可以这样做:

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
}

您甚至可以这样做:

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

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

由于 int 是通过值传递的,所以const不重要。

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.

这篇关于C ++ const问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆