构造函数中缺少表达式

missing expression in a constructor

我有以下 class:

  class BandMember
{
private:
    char *name;
    int age;
    int relationshipStatus;
    char *musicianType;
public:
    //functions
    void setName(char* name1);
    char * getName() const;
    void setAge(int age1);
    int getAge() const;
    void setRelationshipStatus(int status);
    int getRelationshipStatus() const;
    void setMusicianType(char* job);
    char* getMusicianType() const;
    BandMember* readBandMember();
    //print
    void print();

    //constructor
    BandMember(const char *nameToAdd = "no name", const int ageToAdd = 0, 
        const int relationshipStatusToAdd = 0, 
        const char *musicianTypeToAdd = "no music type");

    //destructor
    ~BandMember() { delete[] name; delete[] musicianType;}

    //copy constructor
    BandMember(const BandMember& bandMember);
};

BandMember* BandMember::readMember中的代码是:

 BandMember* BandMember::readBandMember()
{
    char *nameNewMember, *musicTypeNewMember;
    int ageNewMember, familyStatusNewMember;

    nameNewMember = new char[NAME_LENGTH];
    musicTypeNewMember = new char[NAME_LENGTH];

    cin.ignore(10,'\n');
    cout << "Enter band member name: ";   //askName() - TODO
    cin.getline(nameNewMember, NAME_LENGTH);
    reallocate(nameNewMember, strlen(nameNewMember));

    cout << "enter the age of the band member: ";  //askAge - TODO
    cin >> ageNewMember;

    cin.ignore(10,'\n');
    cout << "enter musician type: ";     //askMusicianType - TODO
    cin.getline(musicTypeNewMember, NAME_LENGTH);
    reallocate(musicTypeNewMember, strlen(musicTypeNewMember));

    return new BandMember(nameNewMember, ageNewMember,,musicTypeNewMember);

问题出在 return 值上。 编译器说 "missing expression, overload +1": 但是当我把 return new BandMember(nameNewMember, ageNewMember,0,musicTypeNewMember); 代码工作正常...... 我不明白为什么。 我用默认值定义了一个默认构造器,所以为什么当我 return 它缺少值时它不起作用?

您似乎误解了默认参数在 C++ 中的工作方式...

您不能跳过 参数并将它们设置为默认值。如果你想提供后面的参数,那么你需要在它前面提供 all 个参数。

因此带双逗号的BandMember(nameNewMember, ageNewMember,,musicTypeNewMember)不正确,您还必须提供relationshipStatusToAdd参数:

return new BandMember(nameNewMember, ageNewMember,0,musicTypeNewMember);
//                                                ^
// Added argument here --------------------------/

I defined a default constractor with default values so why it's not working when I return it with a missing value ?

参数的默认值只适用于从右边开始。你不能在中间漏掉一个。

new BandMember(nameNewMember, ageNewMember,,musicTypeNewMember);
                                 //        ^  NOPE!

例如你可以这样称呼它

new BandMember(nameNewMember, ageNewMember);

如果您希望构造函数只接受前两个参数和最后一个参数的参数,那么您需要在这些参数最先出现的地方编写一个构造函数。

I don't understand why

可能没有禁止这样做的技术限制。您使用 ,, 的方式可能是可行的方式。然而,这不是它在 C++ 中的定义方式。