#include <iostream>using namespace std;class Calculator { private: int num1, num2; public: Calculator(int n1, int n2) { num1 = n1; num2 = n2; } int add() { return num1 + num2; }};int main() { int n1, n2; cout << "Enter two numbers:" << endl; cin >> n1 >> n2; Calculator calc(n1, n2); cout << "Sum is: " << calc.add() << endl; return 0;}
时间: 2024-02-16 15:11:18 浏览: 33
这是一个简单的 C++ 程序,实现了一个 Calculator(计算器)类,可以对两个整数进行加法运算。在程序中,用户会被要求输入两个整数,然后创建一个 Calculator 对象,并调用其 add 方法,将计算结果输出到屏幕上。程序中的 class 关键字用于定义类,private 关键字用于声明私有成员变量和方法,public 关键字用于声明公共成员变量和方法。在构造函数中,使用了初始化列表的方式对成员变量进行初始化。
相关问题
补全程序,并写出程序运行结果。 #include <iostream> using namespace std; class Class { public : Class ( int...
补全程序如下:
```
#include <iostream>
using namespace std;
class Class {
public:
Class(int num) {
cout << "Constructor with one argument called." << endl;
}
Class(int num1, int num2) {
cout << "Constructor with two arguments called." << endl;
}
};
int main() {
Class obj1(10);
Class obj2(20, 30);
return 0;
}
```
程序运行结果为:
```
Constructor with one argument called.
Constructor with two arguments called.
```
解释:
这是一个带有两个构造函数的类`Class`。第一个构造函数接受一个整数参数,第二个构造函数接受两个整数参数。在`main`函数中,我们创建了两个对象`obj1`和`obj2`,分别调用了两个不同的构造函数。所以,程序输出了两个不同的消息。
#include<iostream>using namespace std;
这是一个C++的代码片段,它包含了iostream头文件和使用了命名空间std。iostream头文件提供了输入输出流的功能,而using namespace std;语句则是为了方便使用std命名空间中的函数和对象,避免每次都需要写std::。
以下是一个简单的示例代码,展示了如何使用iostream头文件和命名空间std来输出一句话:
```cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
```
这段代码会输出"Hello, World!",endl是一个特殊的控制符,用于在输出流中插入一个换行符。