gpt4 book ai didi

c++ - 将 this 传递给 this 的类变量的方法

转载 作者:行者123 更新时间:2023-11-28 05:31:45 25 4
gpt4 key购买 nike

我的代码中有以下情况,不知道它是否揭示了一些错误的设计。

class A
{
public:
...
void estimateParameters(const std::vector<double> &data);
private:
B m_algorithm;
int m_parameter1;
int m_parameter2;
};

void A::estimateParameters(const sdt::vector<double> &data)
{
m_algorithm.estimate(this, data); // And then m_parameter1 and m_parameter2 are filled
}

estimateParameters 的实现调用Bestimate 方法,该方法接收指向this 的指针作为参数.这对我来说听起来有点奇怪而且似乎是多余的。我正在使用这个方案来封装 A 的参数估计,而不强制用户在他的代码中手动创建 B 的实例,然后传递 A。这是一种使参数估计对用户透明的方法。

这种方案常见吗?你认为这是最好的方法吗?有没有多余或更清晰的替代方案?

谢谢

最佳答案

您的设计让我想起了 Strategy pattern ,在这个例子中这对我来说很有意义。

这里的一个问题是B 依赖于A。您可以通过引用传递参数(而不是 this 指针)来移除这种依赖性。

m_algorithm.estimate(m_parameter1, m_parameter2, data);

另外,定义一个参数类(或结构)可能是有意义的。

struct Parameters {
int m_parameter1;
int m_parameter2;
}

class A {
public:
void estimateParameters(const std::vector<double>& data);
private:
B m_algorithm;
Parameters m_parameters;
};

void A::estimateParameters(const std::vector<double>& data) {
m_algorithm.estimate(m_parameters, data);
}

void B::estimate(Parameters& parameters, const std::vector<double>& data) { ... }

关于c++ - 将 this 传递给 this 的类变量的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39346367/

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