lundi 14 novembre 2022

C++ requires a type specifier for all declarations while assigning values to array of strings [duplicate]

I am a new to C++. I have a class as follows compiling which is throwing "C++ requires a type specifier for all declarations" as the values for array of string elements are being assigned after the array of string is dynamically allocated.

#include <iostream>
#include <string>

using namespace std;

class bank {

protected:
    string* Checkperson = new string[3];
    string managerUsername = "manager";
    string managerPassword = "M@n@ger";
    Checkperson[0] = "First";    //the error is here
    Checkperson[1] = "Last";     //the error is here
    Checkperson[2] = "Manager";  //the error is here
    string* searchFiles(string username, string password) {
        string* person = new string[3];
        for(int i = 0; i < 3; i++) {
            person[i].clear();
        }
        if((username == managerUsername) && (password == managerPassword)) {
            for(int i = 0; i < 3; i++) {
                person[i] = Checkperson[i];
            }
        }
        return person;
    }
};

Compiling this I get the errors:

./bank.cpp:17:2: error: C++ requires a type specifier for all declarations
        Checkperson[0] = "First";
        ^
./bank.cpp:18:2: error: C++ requires a type specifier for all declarations
        Checkperson[1] = "Last";
        ^
./bank.cpp:19:2: error: C++ requires a type specifier for all declarations
        Checkperson[2] = "Manager";
        ^

I tried the following and it worked fine but since I am trying to learn c++ would like to know why the previous method didn't work.

string Checkperson[3] = {"First", "Last", "Manager"};

Aucun commentaire:

Enregistrer un commentaire