C++ 程序:使用类执行基本操作
原文:https://www.studytonight.com/cpp-programs/cpp-performing-basic-operations-using-class
大家好!
在本教程中,我们将学习如何使用 C++ 编程语言中的类及其成员执行基本操作。
为了了解类及其成员的概念,我们将推荐您访问这里: C++ 类概念,我们已经从头开始解释了。
代号:
#include <iostream>
#include <vector>
using namespace std;
//defining the class operations to implement all the basic operations
class operations {
//declaring member variables
public:
int num1, num2;
//defining member function or methods
public:
void input() {
cout << "Enter two numbers to perform operations on: \n";
cin >> num1 >> num2;
cout << "\n";
}
public:
void addition() {
cout << "Addition = " << num1 + num2;
cout << "\n";
}
void subtraction() {
cout << "Subtraction = " << num1 - num2;
cout << "\n";
}
void multiplication() {
cout << "Multiplication = " << num1 * num2;
cout << "\n";
}
void division() {
cout << "Division = " << (float) num1 / num2;
cout << "\n";
}
};
//Defining the main method to access the members of the class
int main() {
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to perform basic operations using Class, in CPP ===== \n\n";
//Declaring class object to access class members from outside the class
operations op;
cout << "\nCalling the input() function from the main() method\n";
op.input();
cout << "\nCalling the addition() function from the main() method\n";
op.addition();
cout << "\nCalling the subtraction() function from the main() method\n";
op.subtraction();
cout << "\nCalling the multiplication() function from the main() method\n";
op.multiplication();
cout << "\nCalling the division() function from the main() method\n";
op.division();
cout << "\nExiting the main() method\n\n\n";
return 0;
}
输出:
我们希望这篇文章能帮助你更好地理解 C++ 中类的概念。如有任何疑问,请随时通过下面的评论区联系我们。
继续学习: