gpt4 book ai didi

c++ - 如何根据bool类型成员函数的返回值调用struct成员函数?

转载 作者:行者123 更新时间:2023-11-28 02:25:12 24 4
gpt4 key购买 nike

我想在结构的 bool 成员函数中做一些条件检查。我的结构对象 struct1 如何知道 bool 成员函数已返回 true,以便整数 a 和 b 可以在 calc 成员函数中使用?

int main() {
vector<Point> pt;
pt.push_back(Point{ 1.5, 4.2 });
pt.push_back(Point{ 2.4, 3.1 });

doSth struct1;
bool tempbool = struct1.memfuncbool(pt); //error starts here!
if (tempbool) {int answer = struct1.calc(1);} //??
std::cout << answer;

return 0;
}

struct Point {
double _x;
double _y;
};

struct doSth {

int a, b; //data members

int calc(const int k) {
return (a + b)*k;
}

bool memfuncbool(const vector<Point> &pts) {

//does stuff...

a = var1; //var1 = 1
b = var2; //var2 = 2

return true;
}
}

最佳答案

有两种方法:调用者安全封装和纯代码规范。稍后您自己确保您编写的代码始终知道 memfuncbool 的最新结果以及 ab 何时何地出现设置。

首先,您可以在调用 memfuncbool 后设置的结构中添加一个标志,并检查计算(并适当处理它)。在这种情况下,您还应该确保在初始化结构时清除该标志 -通过构造函数或再次代码规则(比如总是将你的结构归零)。

第一种意义上的信息隐藏方法 (C++) 看起来像这样:

class DoSth {
int a, b;
bool valid;

public:
DoSth() : valid(false) { }

bool isValid() const { return valid; }

/// returns calc if valid, otherwise 0
int calc(int k) const {
return isValid() ? (a + b) * k : 0;
}

void setSth(...) {
a = ...
b = ...
valid = true;
// instead of returning here the caller can check isValid() anytime
}
};

关于c++ - 如何根据bool类型成员函数的返回值调用struct成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30965993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com