根据设计,在构造函数中使用 istream 运算符是否可以

Is it fine, by design, to use istream operator in constructor

本文关键字:istream 运算符 是否 构造函数      更新时间:2023-10-16

以下是我创建的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.