题目
编写一个具有常量成员函数和非常量成员函数的类。编写三个函数,将该类的一个对象作为参数;第一个按值取值,第二个按引用取值,第三个按常量引用取值。在函数内部,尝试调用类的两个成员函数并解释结果。
代码
#include <iostream>
using namespace std;
class A
{
public:
A(int x){a=x;}
void showa() const {cout << "const: "<<a <<endl;}
void showb(){cout <<"non-const: "<< a <<endl;}
private:
int a;
};
void func1(A a)//按值
{
a.showa();
a.showb();
}
void func2(A& a)//引用
{
a.showa();
a.showb();
}
void func3(const A& a)//常量引用
{
a.showa();
//a.showb(); 错误,无法调用
}
int main()
{
A a(1);
cout<<"func1()"<<endl; func1(a);
cout<<"func2()"<<endl; func2(a);
cout<<"func3()"<<endl; func3(a);
return 0;
}
结果
按值传参 与 引用传参都可以调用func1与func2。
使用常量引用传参,无法调用non-const函数,可以调用const函数。