C++ 组合从 istream 获得的类对象

标签 c++ class

我是 C++ 的新手。这实际上是我正在编写的第一个类(一些代码取自 C++Primer)。尝试组合具有相同名称的类对象时出现逻辑错误。事情是这样的:

  • 我的类(class)持有学生记录:姓名、通过的类(class)数和 总分(计算平均分)
  • 构造函数从istream获取数据

    struct StudentEntry {
        StudentEntry() = default;
        StudentEntry(std::istream &);
    
        std::string getStudentName() const { return name; }
        StudentEntry& combine (const StudentEntry&);
        double avgMark() const;
    
        std::string name = "";
        unsigned passCources = 0;
        double markSum = 0.0;
    };
    
  • combine 函数用于 += 数据成员(passCources & markSum):

    StudentEntry& StudentEntry::combine(const StudentEntry& st) {
        passCources += st.passCources;
        markSum += st.markSum;
        return *this;
    }
    
  • avgMark 正在计算标记平均值:

    double StudentEntry::avgMark() const {
        return passCources ? markSum / passCources : 0;
    }
    
  • 当我在 main 中组合 2 个以上的对象时,我出错了 标记总和和平均值

    int main() {
        StudentEntry st;
        if (read(std::cin, st)) {
            StudentEntry nextSt;
            while (read(std::cin, nextSt)) {
                if (st.getStudentName() == nextSt.getStudentName())
                    st.combine(nextSt);
            }
        }
        print(std::cout, st);
    }
    
  • 结果错误:

    Next -> 
    Nick 1 90
    Next -> 
    Nick 1 90
    Next -> 
    Nick 1 90
    Next -> 
    Nick 3 360   | Average: 120
    
  • 应该是 Nick 3 270 |平均:90

  • 我卡在这里了。

  • 我的printread 函数(和构造函数)。如果通过的类(class)数 > 1,read 应该获得所有后续分数。

    std::ostream& print(std::ostream &os, const StudentEntry &st) {
        os << st.getStudentName() << " " << st.passCources << " " << st.markSum
                << "\t | Average: " << st.avgMark() << "\n";
        return os;
    }
    
    std::istream& read(std::istream &is, StudentEntry &st) {
        std::cout << "Next -> " << std::endl;
        is >> st.name >> st.passCources;
        double mark;
        for (unsigned i = 0; i < st.passCources; ++i) {
            is >> mark;
            st.markSum += mark;
        }
        return is;
    }
    
    StudentEntry::StudentEntry(std::istream &is) {
        read(is, *this);
    }
    

最佳答案

while 循环的每次迭代都会在 nextSt 中累积 markSum 值,因为它调用了 read 方法

st.markSum += mark;

你应该在迭代之前重置总和:

st.markSum = 0.0;
double mark;
for (unsigned i = 0; i < st.passCources; ++i) {
    is >> mark;
    st.markSum += mark;
}

关于C++ 组合从 istream 获得的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48296349/

相关文章:

c++ - 并发安全栈接口(interface)方法 : correct or not?

php - 在php类中生成一个随机数

c++ - 在 CPU 上并行减少数组

c++ - 使用第三方库的菱形继承(钻石问题)问题

c++ - OpenCL中的cuda中是否有类似原子操作的东西

class - TYPO3 v10 持久化映射

java - 在主方法中调用类的构造函数?

python类对象定义

C++ 已弃用从字符串常量到 'char*' 的转换 []

c++ - '{' 标记之前的预期类名。 C++继承