问题
填空题
有以下程序: #include <iostream> using namespace std; class Sample { private: int n; public: Sample(int i){n=i;} void print() {cout<<"1:n="<<n<<","; } void print() const {cout<<"2:n="<<n<<end1; } }; int main() { Sample a(10); const Sample b(20); a.print(); b.print(); } 上述程序运行后的输出结果是 【13】 。
答案
参考答案:1:n=10,2:n=20
解析: 本题考核常成员函数的应用。本程序中,Sample类中说明了两个同名函数print(),其中一个是常成员函数,另一个为普通成员函数。在主函数中说明了两个对象a和b,其中对象b是常对象,通过对象a调用的是普通成员函数print(),通过对象b调用的是常成员函数print()。