难度等级:新手
null
预测下面的C++程序的输出。
问题1
#include<iostream> using namespace std; int x = 10; void fun() { int x = 2; { int x = 1; cout << ::x << endl; } } int main() { fun(); return 0; } |
输出: 10 如果 范围解析运算符 放置在变量名之前,然后引用全局变量。因此,如果我们从上面的程序中删除以下行,那么它将无法编译。
int x = 10;
问题2
#include<iostream> using namespace std; class Point { private : int x; int y; public : Point( int i, int j); // Constructor }; Point::Point( int i = 0, int j = 0) { x = i; y = j; cout << "Constructor called" ; } int main() { Point t1, *t2; return 0; } |
输出: 我打电话来了。 如果我们仔细看一下语句“Point t1,*t2;:”,那么我们可以看到这里只构造了一个对象。t2只是一个指针变量,而不是一个对象。
问题3
#include<iostream> using namespace std; class Point { private : int x; int y; public : Point( int i = 0, int j = 0); // Normal Constructor Point( const Point &t); // Copy Constructor }; Point::Point( int i, int j) { x = i; y = j; cout << "Normal Constructor called" ; } Point::Point( const Point &t) { y = t.y; cout << "Copy Constructor called" ; } int main() { Point *t1, *t2; t1 = new Point(10, 15); t2 = new Point(*t1); Point t3 = *t1; Point t4; t4 = t3; return 0; } |
输出: 正常构造函数调用 复制构造函数调用 复制构造函数调用 正常构造函数调用
有关解释,请参见以下注释:
Point *t1, *t2; // No constructor call t1 = new Point(10, 15); // Normal constructor call t2 = new Point(*t1); // Copy constructor call Point t3 = *t1; // Copy Constructor call Point t4; // Normal Constructor call t4 = t3; // Assignment operator call |
如果您发现任何答案/解释不正确,或者您想分享有关上述主题的更多信息,请发表评论
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END