为什么编译器在类构造函数之前要求初始化?

How come the compiler asks for initializer before class constructor?

本文关键字:初始化 编译器 构造函数 为什么      更新时间:2023-10-16

我正在创建一个名为SelectionPage的类。它本质上是一组菜单。

然而,当我编译代码时,编译器给了我以下错误:

g++ C_Main.cpp C_HomePage.cpp C_SelectionPage.cpp C_MemberManagement.cpp -o Project
C_SelectionPage.cpp:9:104: error: expected initializer before ‘SelectionPage’
make: *** [Project] Error 1

下面是C_SelectionPage.cpp的前几行:

#include "H_SelectionPage.h"

//Constructor for the SelectionPage class
//It assigns "managing" which decides if the user
//is a manager or not.
SelectionPage::SelectionPage(
    int newPoints,
    string newManager,
    string newLoginName,
    string MemberFile)
        SelectionPage(
            int newPoints,
            string newManager,
            string newLoginName,
            string MemberFile)
    {
        points = newPoints;
        manager = newManager;
        loginName = newLoginName;
        flatMemberList.clear();
        //Create Object Governing Flat Members.
        memberList = MemberManagement temp(MemberFile);
}
下面是头文件中构造函数的声明:
SelectionPage(
    int newPoints,
    string newManager,
    string newLoginName,
    string MemberFile);

有人能告诉我为什么我得到一个错误吗?

如果您的代码中确实有这一行,那么您可能复制了两次构造函数:

SelectionPage::SelectionPage(int newPoints, string newManager, string newLoginName, string MemberFile )SelectionPage( int newPoints, string newManager, string newLoginName, string MemberFile){

应该是这样的:

SelectionPage::SelectionPage(int newPoints, string newManager, string newLoginName, string MemberFile ){

编译器抱怨初始化列表,因为它应该在头文件后面,而不是参数列表的另一个副本。

尝试在SelectionPage前面添加访问说明符

您可以在构造函数初始化列表中执行一些初始化,而在构造函数体中执行其余初始化。

SelectionPage::SelectionPage(
  int newPoints, 
  string newManager, 
  string newLoginName, 
  string MemberFile)
  : points(newPoints)
  , manager(newManager)
  , loginName(newLoginName)
  , memberList(MemberFile)
{
  // do the rest initialization here
}