将公共代码移动到基类是假设没有的好习惯吗?

zar*_*zar 2 c++ architecture oop code-reuse

我需要打印定期报告和批量报告.我正在使用podofo库.我计划为每个报告使用单独的类,但每个类将需要下面的一些常用函数(现在在另一个项目的一个类中).

int CPdfBatchReport::CalculateMaxRowsInEmptyPage(void)
{
    int rows = MaxPageHeight / PDF_TABLE_STANDARD_ROW_HEIGHT;

    // because the first will always be the column header in every page, we substrct 1 to account for that
    rows = rows - 1;

    return rows;
}

// Calculates the max rows in current page. The current page is determined 
// by the current x, y position
int CPdfBatchReport::CalculateMaxRowsInCurrentPage(void)
{
    float AvailablePageHeight =  pPage->GetPageSize().GetHeight() - PDF_BOTTOM_MARGIN - y;

    int rows = AvailablePageHeight / PDF_TABLE_STANDARD_ROW_HEIGHT;

    // because the first will always be the column header in every page, we substrct 1 to account for that
    rows = rows - 1;

    return rows;
}


void CPdfBatchReport::StartPage(void)
{
    x = PDF_LEFT_RIGHT_MARGIN;
    y = PDF_TOP_MARGIN;
}
Run Code Online (Sandbox Code Playgroud)

使用这个公共代码创建基类并在派生类中进行实际打印是否有意义?这是一个好习惯吗?

所以基本上我会让基类说出PrintBase上面的函数和两个派生类PrintBatchReport,PrintItemReport它们实际上将使用这些函数.

Mat*_*son 6

是的,将公共代码放在基类中绝对是个好主意."不要重复自己" - 干 - 是一种很好的编程风格.避免复制粘贴编程.

您不希望基类中的内容的唯一时间是它是一个接口类.但在这种情况下似乎并非如此.