程序没有在一个总计变量中加起来来自所有不同办事处的股票

program not adding up the shares from all different offices in one TotalAmount variable

本文关键字:起来 办事处 变量 程序 一个      更新时间:2023-10-16

我在C 中学习OOP,该程序旨在从不同的办公室收集股票,并将每个办公室的股份存储在名为SharePeroffice的变量中,并将所有办公室的这些股份添加到一个单一可变中(总计((请参阅班级国家佛教徒的私人成员(..但它没有在TotalAmount变量中添加它们。

#include<iostream>
#include<cstdlib>
using namespace std;
class nationalOffices
{
private:
    int sharePerOffice;
    int totalShare;
public:
    nationalOffices();
    nationalOffices(int x);
    void setsharePerOffice(int value);
    void setTotalShare();
    int getTotalShare();
};
nationalOffices::nationalOffices()
{
    sharePerOffice = 0;
}
nationalOffices::nationalOffices(int x)
{
    totalShare = x;
    sharePerOffice = 0;
}
void nationalOffices::setsharePerOffice(int value)
{
    sharePerOffice = value;
}
void nationalOffices::setTotalShare()
{
    totalShare = totalShare + sharePerOffice;
}
int nationalOffices::getTotalShare()
{
    return totalShare;
}
int main ()
{
    int shares = 0;
    nationalOffices offices[5] = {0};
    for (int i = 0; i < 5; i++)
    {
        cout <<"enter share for office number "<<i+1<<": ";
        cin >> shares;
        offices[i].setsharePerOffice(shares);
        offices[i].setTotalShare();
        system("cls");
    }
    cout <<endl;
    cout <<offices[0].getTotalShare();
}

变量offices是五个不同且独特且唯一的nationalOffices对象的数组。每个对象都有其自己的成员变量集。

totalShare成员对于每个对象都是唯一的,并且与其他每个对象的成员变量无关。

而不是将其作为成员变量,而是将总计添加到main函数内的本地变量。

另一个可能的解决方案是使 totalShare成为 static成员变量,在这种情况下,它变成了 class 变量,由类的所有对象共享。

相关文章: