如何将类分隔到多个文件?以下是我目前的理解:
我知道有更简单的方法来做这样的事情,但是为了练习,我选择使用类和对象。
- 创建新的类,并为其创建一个“.h”文件和一个“.cpp”文件。
- 在主源文件中使用
#include classname.h
导入其内容。 - 源文件开头的
Classname::Classname
是作用域解析运算符。 - 通过使用已声明的对象,您可以从
main
调用函数。
#include <iostream>
using namespace std;
class Addition {
public:
float add(float x, float y) {
float sum;
sum = x + y;
return sum;
}
};
class Subtraction {
public:
float subtract(float x, float y) {
float dif;
dif = x - y;
return dif;
}
};
class Multiplication {
public:
float multiply(float x, float y) {
float prod;
prod = x * y;
return prod;
}
};
class Division {
public:
float divide(float x, float y) {
float quot;
quot = x / y;
return quot;
}
};
int op;
char cont;
int main() {
do {
cout << "Welcome to C++ Calculator v2!" << endl;
cout << "Select the number for which operation you want to use: " << endl;
cout << "1-Addition" << endl;
cout << "2-Subtraction" << endl;
cout << "3-Mutliplication" << endl;
cout << "4-Division" << endl;
cin >> op;
if (op == 1) {
float num1;
float num2;
Addition addObj;
cout << "You have chosen Addition!" << endl;
cout << "Enter the first number you want to add: " << endl;
cin >> num1;
cout << "Enter the second number you wat to add: " << endl;
cin >> num2;
float ans = addObj.add(num1, num2);
cout << "The sum is " << ans << endl;
cout << "Do you wish to continue? Y/N" << endl;
cin >> cont;
}
if (op == 2) {
float num1;
float num2;
Subtraction subObj;
cout << "You have chosen Subtraction!" << endl;
cout << "Enter the first number you want to subtract: " << endl;
cin >> num1;
cout << "Enter the second number you want to subtract: " << endl;
cin >> num2;
float ans = subObj.subtract(num1, num2);
cout << "The difference is " << ans << endl;
cout << "Do you wish to continue? Y/N" << endl;
cin >> cont;
}
if (op == 3) {
float num1;
float num2;
Multiplication multObj;
cout << "You have chosen Multiplication!" << endl;
cout << "Enter the first number you want to multiply: " << endl;
cin >> num1;
cout << "Enter the second number you want to multiply: " << endl;
cin >> num2;
float ans = multObj.multiply(num1, num2);
cout << "The product is " << ans << endl;
cout << "Do you wish to continue? Y/N" << endl;
cin >> cont;
}
if (op == 4) {
float num1;
float num2;
Division divObj;
cout << "You have chosen Division!" << endl;
cout << "Enter the first number you want to divide: " << endl;
cin >> num1;
cout << "Enter the second number you want to divide: " << endl;
cin >> num2;
float ans = divObj.divide(num1, num2);
cout << "The quotient is " << ans << endl;
cout << "Do you wish to continue? Y/N" << endl;
cin >> cont;
}
} while (cont == 'Y' || cont == 'y');
if (cont == 'N' || 'n') {
cout << "Thanks for using my program, goodbye!" << endl;
}
return 0;
}
我知道有更简单的方法来做这样的事情,但是为了练习,我选择使用类和对象。