C++ - 如何在不调用其属性的情况下调用类?

C++ - How can we call a class without calling its attributes?

本文关键字:调用 属性 情况下 C++      更新时间:2023-10-16

我需要为学校练习实现类Multiplier,但我不明白老师如何在不调用其输入的情况下调用prod()

代码的目标是读取整数序列,直到其绝对值的乘积大于 200。

有人可以帮助我理解吗?

这是代码:

#include <iostream>
using namespace std; 
int main()
{
Product mult(200); 
cout << "Enter numbers: " << endl;
do{
cin >> mult;
} while(!mult.exceed_limit()); 
cout << "The absolute values product is " << mult() << " . " << endl; 
return 0; 
}

类可以通过重载operator()成员函数来实现"调用"操作。

例如

class MyType {
public:
void operator()(int param) const {
std::cout << "MyType(int) called with: " << param << "n";
}
void operator()() const {
std::cout << "MyType() calledn";
}
};
int main() {
MyType  instance;
instance(12);
instance();
return 0;
}

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()(然后返回值通过operator<<流式传输到cout(,例如:

class Multiplier
{
...
public:
int operator()() const;
...
};

让我们看看我们需要什么

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有点罕见,但这没关系。

现场演示