#include <iostream> using namespace std; class Test { private: int x; public: Test(int x) { this->x=x; } void show(){ cout<<x<<endl; } }; int main(){ Test b=(2,3,55); b.show() ; return 0; }为什么b中x会是55呢
时间: 2024-04-22 18:22:42 浏览: 16
在这段代码中,`Test b=(2,3,55);`这一行代码其实是利用了逗号运算符。在C++中,逗号运算符可以连续使用,每个逗号之间的表达式都会被计算,但整个表达式的值只取最后一个表达式的值。
因此,`(2,3,55)`表达式中,逗号运算符会先计算`2,3`,但是这个表达式没有任何作用,然后再计算`55`,将其作为参数传递给`Test`类的构造函数。因此,创建对象`b`时,传递给构造函数的参数是`55`,所以`b`中的`x`值是`55`。
相关问题
#include <iostream> using namespace std; class Test{ public: Test(int xx=1):x(xx){} void output(){ cout<<"x: "<<x<<endl; } private: int x; }; int main() { Test t; t.output(); t=4; t.output(); return 0; }
这段代码的输出结果为:
```
x: 1
x: 4
```
首先定义了一个名为 Test 的类,有一个参数为整型的构造函数和一个名为 output 的成员函数。在 main 函数中,首先创建了一个名为 t 的 Test 类对象,并调用其 output 函数,输出 x 的值为 1。接着将整型值 4 赋值给对象 t,此时 t 的 x 值变为 4,再次调用 t 的 output 函数,输出 x 的值为 4。
【单选题】 #include<iostream> using namespace std class Test{ public: Test(){n+=2;} ~Test(){n-=3;} static int getNum(){return n;} private: static int n;}; int Test::n=1; int main() {Test *p=new Test; delete p; cout<<"n="<<Test::getNum()<<endl; return 0;}分析代码
本程序的输出结果为:n=-1。该程序定义了一个Test类,类中静态成员变量n的初始值为1。在main函数中,创建了一个Test类的对象p,然后又立即释放了该对象的内存空间。在创建p对象的过程中,由于调用了Test类的构造函数,n的值加2,所以n的值变为了3。在释放p对象的过程中,由于调用了Test类的析构函数,n的值减3,所以n的值变为了-1。最终,程序输出n的值为-1。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)