C++ - 如何在不调用其属性的情况下调用类?
C++ - How can we call a class without calling its attributes?
我需要为学校练习实现类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
有点罕见,但这没关系。
现场演示
相关文章:
- C++调用具有 *this 属性的单个帮助程序函数
- C++:从属性类调用顶级类方法
- 类对象属性是否可以调用返回属性应具有的值的方法C++?
- C++ - 如何在不调用其属性的情况下调用类?
- CMake 设置使用不正确的参数数调用的目标属性
- 通过指针算法调用结构的结构属性
- 使用类属性调用具有非类型模板参数的模板函数
- 如何将按钮添加到节点的属性编辑器面板,该面板调用该节点内的方法?
- 如何调用 ActiveX 控件的属性页?
- 如何使用结构实例的名称调用其属性
- 远程过程调用和MIDL:如何使用[OUT]属性实现功能
- observeValueForKeyPath没有为持有C++对象的属性调用
- 如何从 C# 调用C++本机属性
- Rcpp编译的属性不可用于调用
- C++:父对象在不调用方法的情况下更改其id属性
- 属性错误:"模块"对象没有属性"func",仅通过C++调用
- (初学者模式)调用时变量的属性
- 如何使用V8从C++访问和调用Javascript对象属性和方法
- 创建一个具有调用策略的属性- boost::python
- 如何在c++中动态调用属性名,就像JS中的方括号符号一样