Most existing studies on aerodynamic shape optimization have not considered longitudinal trim under control surface deflection, typically achieving self-trim through a constraint of zero pitching moment or adjusting the optimized configuration for longitudinal trim. However, adjustments to the optimized configuration might introduce additional drag, reducing overall optimization benefits. In this paper, a novel approach of incorporating control surface deflection for longitudinal trim in aerodynamic optimization is proposed. Firstly, an aerodynamic computation program based on the high-order panel method was developed, introducing velocity perturbations on specific mesh surfaces to simulate actual control surface deflections. Subsequently, a comprehensive optimization framework was established, encompassing parametric modeling, aerodynamic computation, and variable-fidelity control surface deflection analysis. Finally, aerodynamic optimization analysis was conducted under both subsonic and supersonic conditions. Thirty-one design variables were selected with the trimmed lift-to-drag ratio in cruising condition as the objective function and the control surface deflection angle as the constraint. The results indicated an 8.52% increase in the trimmed lift-to-drag ratio compared to the baseline model under subsonic conditions and an 8.1% increase under supersonic conditions.