c++ - 使用私有(private)变量获取正确值时遇到问题

标签 c++

这是一个程序,它接受一个数组并使用类打印该数组的奇数(命名为 m_sumOdd)和偶数(命名为 m_sumEven)之和。但是,当我运行它并输入一些值(4、6、9、3、1)时,m_sumEven 返回 10,m_sumOdd 返回 2037769787。 m_sumOdd 有什么问题?

#include <iostream>
#include <string>

class myClass {
private:
int m_sumEven;
int m_sumOdd;
public:
    myClass() {
        m_sumEven = 0;
        m_sumOdd = 0;
    }
    myClass(int arr[]) {
        for (int  i = 0; i < 5; i++)
        {
            if (arr[i] % 2 == 0) {
                m_sumEven += arr[i];
            }
            else if (arr[i] % 2 != 0) {
                m_sumOdd += arr[i];
            }
        }
        print();
    }
    void print() {
         std::cout << m_sumEven << "\t" << m_sumOdd << std::endl;
    }
};

int main(){

    int main_arr[5];

    for (int j = 0; j < 5; j++)
    {
         std::cin >> main_arr[j];
    }

    myClass obj(main_arr);


    std::cin.get();
}

最佳答案

从您的评论中:

the problem is from my uni textbook and it specify that the private variables shall be initialized in the default constructor and the other constructor find the sum


我不确定教科书正在寻找什么解决方案,但有一种机制允许一个构造函数使用另一个构造函数。
class myClass {
private:
    int m_sumEven;
    int m_sumOdd;
public:
    myClass() {
        m_sumEven = 0;
        m_sumOdd = 0;
    }
    myClass(int arr[]): myClass() { // <-------
        ....
这称为 delegating constructors .这使您的 myClass(int arr[])构造函数使用 myClass()在继续之前的构造函数。

关于c++ - 使用私有(private)变量获取正确值时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62628374/

相关文章:

c++ - `std::string` 是否在内部将其字符存储为签名字符?

c++ - 如何使用 CGAL 存储折叠的边缘

c++ - c++ 中的可选引用是否保留对象生命?

c++ - 如何从自己类的成员函数中访问公共(public)变量? (C++)

c++ - 配置 g++ 以使用 wxwidget 库构建 c++

c++ - BSTR 转换为 UTF-8

c++ - 创建 constexpr 模板函数以对 C++ 中的任何容器求和

c++ - 错误写入 Excel 文件 - C++

c++ - 信号 - 循环内的槽连接

c++ - 如何在 parasoft cpptestcli 中设置编译器路径?