根据设计,在构造函数中使用 istream 运算符是否可以
Is it fine, by design, to use istream operator in constructor
以下是我创建的linear_program
类的构造函数的C++代码。问题是我有一种感觉,根据设计,我应该重载这个类的>>
运算符,而不是只在类的构造函数中使用>>
它。但是我必须动态分配内存,这取决于所采用的输入,所以我不能完全隔离逻辑,即使我重载运算符,我也无法一次接受所有输入。这就是为什么我认为在这种情况下超载>>
没有好处。
linear_program::linear_program() {
cin >> dim >> no_constr;
lp = new plane[no_constr];
double *temp = new double [dim];
double constant;
for (int i = 0; i < no_constr; ++i) {
for (int j = 0; j < dim;++j) {
cin >> temp[j];
}
cin >> constant;
lp[i].set_plane(temp, constant, dim);
}
for (int i = 0; i < no_constr; ++i) {
cin >> cost[i];
}
}
按照设计标准,这是可以接受的吗?我还想知道在这种情况下是否有其他健康的替代方案。
取决于你所说的"罚款"是什么意思。但我建议将对象初始化保留在构造函数中,并将业务逻辑(与该对象的创建不对应)移动到另一个函数。
构造函数应该初始化对象,仅此而已。
linear_program::linear_program(int dim, int no_constr):
m_noConstr(no_constr), m_Dim(dim)
{
lp = new plane[no_constr];
double constant;
}
void linear_program::get_something()
{
double *temp = new double [m_Dim];
for (int i = 0; i < m_noConstr; ++i) {
for (int j = 0; j < m_Dim;++j) {
cin >> temp[j];
}
cin >> constant;
lp[i].set_plane(temp, constant, dim);
}
for (int i = 0; i < no_constr; ++i) {
cin >> cost[i];
}
}
//Call get_something() after the object has been initialized. It makes reading the code easier.
相关文章:
- iStream 运算符跳过空格字符
- 如何为缺少预定义运算符而不扩展命名空间"std"的标准类型定义运算符>> (istream &, ...)?
- C++使 ostream 和 istream 运算符过载
- Istream 运算符重载'>>'导致无限循环
- 使用 getline 重载 istream 运算符>> 会出错
- 错误:"运算符>>"不匹配 重载 istream 运算符
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- 错误在模板类中调用过载的ISTream运算符
- C++ istream 运算符>>不良数据处理
- 继承 istream 运算符>>
- 将 istream 运算符>>转换为 istream getline
- std::istream&运算符>>和自己的向量类
- istream 运算符重载>>将不起作用
- 将 istream 运算符与类交朋友
- std::istream 运算符异常重置/未抛出
- C++istream运算符重载-即使声明为友元,也无法访问数据成员
- C++ istream 运算符 >>
- C++ iStream 运算符>>期望任意输入类型
- 重载 istream 运算符>> c++
- 根据设计,在构造函数中使用 istream 运算符是否可以