玩类,对象和构造函数/C++

Playing with Classes, Objects and Constructors / C++

本文关键字:C++ 构造函数 对象 玩类      更新时间:2023-10-16

我正在尝试使用 c++ 制作计算器应用程序,使用类和构造函数只是为了练习。我创建了一个包含 4 个函数的类,每个函数对应每个运算符。在 main 函数中,我使用 if 语句来选择数学运算符,一个用于存储用户输入的向量。这个向量将分别执行到类的构造函数和函数。

这是我的代码:

#include <iostream>
#include <vector>
using namespace std;
class Calc {
public:
Calc(vector<int> vec)
{
numbers = vec;
}
int add()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total += numbers[i];
}
return total;
}
int sub()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total = total - numbers[i];
}
return total;
}
int mul()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total = total * numbers[i];
}
return total;
}
int div()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total += numbers[i];
}
return total;
}
private:
vector<int> numbers;
};
int main()
{
int operation;
cout << "nEnter the digit that corresponds to the wanted operation:n1. +n2. -n3. *n4. /nn";
cin >> operation;
if (operation != 1 && operation != 2 && operation != 3 && operation != 4)
{
cout << "Invalid entry.";
return 0;
}
cout << "nEnter the numbers followed with a 0 to get the result: ";
int num = 1;
vector<int> nums;
while (num != 0)
{
cin >> num;
nums.push_back(num);
}
Calc Inputs(nums);
if (operation == 1)
{
cout << Inputs.add();
}
else if (operation == 2)
{
cout << Inputs.sub();
}
else if (operation == 3)
{
cout << Inputs.mul();
}
else if (operation == 4)
{
cout << Inputs.div();
}
else 
{
cout << "Invalid entry.";
return 0;
}
}

prgoram 运行完美,直到我输入要计算的数字。谁能帮我找出我的代码有什么问题。

在C++索引中,从 0 开始,一直到numbers.size() - 1

numbers[numbers.size()]

将在向量最后一个条目(又名越界访问(之后访问元素,并导致未定义的行为,这可能导致分段错误。

正确的是

for (int i = 0; i < numbers.size(); i++) { total += numbers[i]; }

或者让编译器完成艰苦的工作并使用基于范围的循环:

for(auto i : numbers) { total += i; }