C ++是否可以保证调用成员函数的某个常量?

时间:2011-04-07 17:44:47

标签: c++ const

如果我有以下内容:

class A {
    int foo() const {
       j++;
       return i;
    }

    int& foo() {
       return i;
    }

    int i;
    mutable int j;
};

然后显然像

A a;
a.foo() = 5;

调用非const版本。但是需要满足哪些条件才能确保调用const或非const版本的例子......

int i = a.foo(); //I would expect to call the const. Is it guaranteed?

const int j = a.foo(); //Ditto

const int& l = a.foo(); //Ditto

int& k = a.foo(); //I would expect the non-const
foobar(k); //foobar is "void foobar(int)"
return; //but the compiler could potentially decide the const version is fine.

4 个答案:

答案 0 :(得分:4)

当对象本身为const时,会调用

const函数。

int i = static_cast<const A>(a).foo(); //calls const function

另请参阅此代码以便更好地理解:( 必须阅读评论

void f(const A &a) //a is const inside the function
{
    int i = a.foo(); // calls const function
}
void h(A &a) //a is non-const inside the function
{
    int i = a.foo(); // calls non-const function
}

A a;
f(a);
h(a); //pass the same object!

参见在线演示:http://ideone.com/96flE

答案 1 :(得分:3)

a的常量决定了哪个函数 - 你对返回值的处理不是重载决策的一部分。你的所有样本都会调用非const版本。

答案 2 :(得分:3)

在确定要采取的过载时,从不考虑返回值。

此外,当a被声明为

A a;

然后非const版本优先。

如果a被声明为

const A a;

然后只能调用const版本。

答案 3 :(得分:1)

你的成员函数调用是否解析为const成员函数,取决于“this”指针的常量,即点或箭头操作符的LHS上隐含传递给被调用成员函数的对象。

解析为非const:

A a;
a.foo();

解析为const:

void bar(const A& a)
{
   a.foo();
}