-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathval.cpp
More file actions
56 lines (51 loc) · 1.6 KB
/
Copy pathval.cpp
File metadata and controls
56 lines (51 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "val.h"
using namespace std;
Value Value::operator+(const Value& op) const {
if (isInt() && op.isInt()) {
return getInt() + op.getInt();
}
else if (isStr() && op.isStr()) {
return getStr() + op.getStr();
}
throw string("Can only add int + int or str + str");
}
Value Value::operator-(const Value& op) const {
if (isInt() && op.isInt()) {
return getInt() - op.getInt();
}
else if (isStr() && op.isStr()) {
if (getStr().find(op.getStr()) == string::npos) {
// Returns the original string if the operand is not a substring of
// the original string
return Value(getStr());
}
return Value(getStr().replace(getStr().find(op.getStr()), op.getStr().length(), ""));
}
throw string("Can only subtract int - int or str - str");
}
Value Value::operator*(const Value& op) const {
if (isInt() && op.isInt()) {
return Value(getInt() * op.getInt());
}
else if ((isStr() && op.isInt()) || (isInt() && op.isStr())) {
string rtn = "";
if (isStr()) {
for (int i=0; i<op.getInt(); i++) {
rtn.append(getStr());
}
}
else if (op.isStr()) {
for (int i=0; i<getInt(); i++) {
rtn.append(op.getStr());
}
}
return Value(rtn);
}
throw string("Can only multiply int * int or str * int");
}
Value Value::operator/(const Value& op) const {
if (isInt() && op.isInt()) {
return Value(getInt() / op.getInt());
}
throw string("Can only divide int / int");
}