尝试从 C++ 中的 class return 布尔值

Trying to return a Bool Value from a class in C++

我对编码和 C++ 的世界还很陌生。我的任务是从具有不同值行的 .txt 文档中获取数字。我需要对每一行进行错误检查以确保文件格式正确。我希望制作一个可以重复使用的 class 来进行这些检查。我,即:

  1. 从第一行获取数据
  2. 检查数据是否符合条件(在这种情况下它必须是 1 或 0,稍后我将不得不根据这个值应用不同的操作)
  3. 根据结果在主文件中触发 true / false if 语句。

Main.cpp

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    #include <functional>
    #include "ErrorSwitch.h"
using namespace std;

//Set pointer of 'file' to beginning line of 'num'
fstream& GotoLine(fstream& file, unsigned int num) {
    file.seekg(ios::beg);
    //Loop through file
    for (int i = 0; i < num - 1; ++i) {
        file.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    return file;
}
int main() {
    fstream file("file1.txt");
    //Check Line 1
    GotoLine(file, 1);
    //Get Input from First Line & Convert to int
    string line1;
    file >> line1;
    int inpu = stoi(line1);
    //Error Check
    ErrorSwitch checkOne;
    checkOne.input = inpu;
    checkOne.errorCheck();
    if (checkOne == true) { //I can't seem to get this to work as a boolean check
        //Do code here
    }
    else if (checkOne == false) {
        //Do code here
    }
    
}

ErrorSwitch.h

#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
using namespace std;

class ErrorSwitch
{
public:
    int input;

    bool errorCheck() {
        switch (input) {
        case 0:
            return true;
            break;
        case 1:
            return true;
            break;
        default:
            return false;
        }
    }
};

有人可以看看这个并帮助我理解如何从这个 class 函数中获得 return 值。 谢谢!

改变这个:

checkOne.errorCheck();
if (checkOne == true) {
    //Do code here
}
else if (checkOne == false) {
    //Do code here
}

为此:

if (checkOne.errorCheck()) {
    //Do code here
}
else {
    //Do code here
}

布尔值是 return 从函数 errorCheck 编辑的,而不是 class 本身。

您可以将 return 值存储到这样的变量中:

    bool checkRes = checkOne.errorCheck();
    if (checkRes == true) {
        //Do code here
    }
    else if (checkRes == false) {
        //Do code here
    }

或者简单地做:

    if (checkOne.errorCheck()) {
        //Do code here
    }
    else { // if bool is not true, it is false
        //Do code here
    }

或者,您可以像这样添加一个运算符将 class 转换为 bool

    operator bool() {
        return errorCheck();
    }

到 class ErrorSwitch 使此代码工作:

    if (checkOne == true) { //I can't seem to get this to work as a boolean check
        //Do code here
    }
    else if (checkOne == false) {
        //Do code here
    }