1.查找以下C ++程序的输出。
#include<iostream>
using namespace std;
class A
{
public :
int x=20;
};
class B
{
public :
int x=10;
};
int main(){
A obj1;
B obj2;
obj1 = obj2;
cout<< obj1.x;
cout<<endl;
return 0;
}输出结果
The program will not generate output due to compilation error.
说明
在此程序中,由于obj1 = obj 2的编译错误,程序无法生成输出。因为在C ++中,我们不能对不同类的不同对象使用算术运算。
正确的代码应为:
#include<iostream>
using namespace std;
class A
{
public :
int x=20;
};
class B
{
public :
int x=10;
};
int main(){
A obj1;
B obj2;
obj1.x = obj2.x;
cout<< obj1.x;
cout<<endl;
return 0;
}2.查找以下C ++程序的输出。
#include<iostream>
using namespace std;
class Test
{
private :
int marks = 85;
public :
Test(int marks)
{
cout<< this->marks;
cout<<endl;
}
};
int main(){
Test t(95);
return 0;
}输出结果
85
说明
通过了解以下步骤,我们可以了解上述程序。
步骤1 –
在主函数中,通过传递整数值95,使用参数构造函数声明Test类的变量t。
步骤2 –
在Test类中,标记的值由整数85初始化。
步骤3 –
在Test类的Test中,此指针用于打印标记。众所周知,构造函数传递的变量标记的值为95,但是由于有了该指针,标记的取值才是在类中初始化的值。因此,该程序的输出为85。