说出const型成员函数能不能调用非const成员函数。

2025-04-30 00:13:45
推荐回答(2个)
回答1:

第一种情况:const对象调用非const成员函数

view plaincopy to clipboardprint?
class A
{
public:
A(int N = 0);
void Fun();
private:
int n;
};
A::A(int N):n(N)
{
}
void A::Fun()
{
cout << n << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
A a;
a.Fun();

const A &b = a;
b.Fun();//const引用的对象调用非const成员函数

//const A a;
//a.Fun();//const对象调用非const成员函数

cin.get();
return 0;
}

当使用const对象调用非const成员函数时编译会报错:error C2662: 'A::Fun' : cannot convert 'this' pointer from 'const A' to 'A &'

报错原因:因为const对象在调用成员函数时会隐含的把实参把中*this修改成const class * const this,以导致非const成员函数在接收时还是使用了class *const this接收,结果就是把const的指针赋给非const的指针

修正方法:以前错误只需在对象的成员函数后面加上const即可

view plaincopy to clipboardprint?
class A
{
public:
A(int N = 0);
void Fun() const;
private:
int n;
};
A::A(int N):n(N)
{
}
void A::Fun() const
{
cout << n << endl;
}

第二种情况:在const成员函数中修改非const成员

view plaincopy to clipboardprint?
class A
{
public:
A(int N = 0);
void Fun() const;
protected:
private:
int n;
};
A::A(int N):n(N)
{
}
void A::Fun() const
{
n = 100;//在const成员函数中修改了成员变量n的值
cout << n << endl;
}
同样,在编译此类时会报错:error C2166: l-value specifies const object

原因:在const的成员函数中修改了成员变量的值

回答2:

const函数中调用的非const函数可以修改类成员,
这样你的const函数不就间接修改类成员了吗?
c++明确规定const函数不可以修改类成员。