我需要在学校练习中实施FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
班,但是我不明白老师如何在不调用输入的情况下调用Multiplier
。
代码的目标是读取整数序列,直到它们的绝对值的乘积大于200。
有人可以帮助我理解吗?
这是代码:
prod()
答案 0 :(得分:3)
类可以通过重载operator()
成员函数来实现“调用”操作。
例如
class MyType {
public:
void operator()(int param) const {
std::cout << "MyType(int) called with: " << param << "\n";
}
void operator()() const {
std::cout << "MyType() called\n";
}
};
int main() {
MyType instance;
instance(12);
instance();
return 0;
}
答案 1 :(得分:2)
Multiplier prod(100);
-Multiplier
必须定义一个构造函数,该构造函数将整数作为输入,例如:
class Multiplier
{
...
public:
Multiplier(int value);
...
};
cin >> prod
-Multiplier
必须过载operator>>
才能输入,例如:
class Multiplier
{
...
};
istream& operator>>(istream&, Multiplier&);
prod.limit_exceeded()
-Multiplier
必须定义了成员limit_exceeded()
方法,例如:
class Multiplier
{
...
public:
bool limit_exceeded() const;
...
};
cout << prod()
-Multiplier
必须重载operator()
(然后将返回值通过cout
流到operator<<
),例如:
class Multiplier
{
...
public:
int operator()() const;
...
};
答案 2 :(得分:1)
让我们看看我们需要什么
int main()
{
Multiplier prod(3);
构造函数。该参数可能是要乘的因子数。
std::cout << "Enter numbers: " << std::endl;
do{
std::cin >> prod;
一种“输入”因素的方法。
} while(!prod.limit_exceeded());
一种查看输入的因子是否等于所需因子数量的方法。
std::cout << "The product of the absolute values is " << prod() << " . " << std::endl;
返回结果产品的调用运算符。
return 0;
}
那么,让我们这样做吧
struct Multiplier {
Multiplier(size_t n) : max_factors(n),num_factors(0),product(1) {}
size_t max_factors;
size_t num_factors;
double product;
double operator()() const { return product;}
bool limit_exceeded() const { return max_factors <= num_factors;}
};
构造函数采用多个因子,product
保存结果,operator()
返回结果,limit_exceeded()
检查是否已输入所有因子。最后,operator>>
的过载读取了以下因素:
std::istream& operator>>(std::istream& in, Multiplier& m){
double x;
if (in >> x) {
m.product *= x;
++m.num_factors;
}
return in;
}
std::cin >> prod;
不读prod
而是修改prod
有点不常见,但这没事。