Declaring a variable as a data type of a class without calling the constructor of the class?

Forgive me if I just explicitly miss something, but I'm trying to make the transition from structures and c to classes and C ++.

Here is what I am trying to do:

A have a "Checkers" class and a "Council" class.

Now with structs, I could just create an array of Checkers in my file "board.cpp" by doing:

Checker checkers[2][12]

(0 and 1 for each side, 0-11 for each part)

The problem is that with classes the execution of the same declaration will try to call the "Checkers" constructor. I get this error: "error: there is no corresponding function to call" Checker :: Checker () "

The constructor of My Checker deals with the initialization of a separate part (for example, if it is on the 0 or 1 side, pieces 0-11), so I did not want to call it.

Is there a way to avoid this, or am I going to do it wrong? Thank.

EDIT: Or maybe I just need to design a constructor to initialize the array of checkers? Can you even declare variables as the data type of a class / object?

+3
source share
5 answers

Create a default constructor. Then use the initial function. I recommend you use the STL vector.

+2
source

Checker Checker Board . , .

+5

, "". : "error: " Checker:: Checker() "

( ), . .

.

std::vector<std::vector<Checker> > checkers;
+1

, . , , , .

, ? , - , ?

, , :

enum Side { White, Black };

class Checker
{
    Side side ;
public:
    Checker ( Side side ) : side(side) {
    }
};


int main()
{
    Checker white[12] = { White, White, White, White, White, White, White, White, White, White, White, White, };
    Checker black[12] = { Black, Black, Black, Black, Black, Black, Black, Black, Black, Black, Black, Black, };
    Checker* both[2] = { white, black };

    return 0;
}

:

    Checker white[12] = { Checker(White,0), Checker(White,1) ...

, , , , , .

+1

, "Checker". , ...

, Checker , , . IYSWIM , - , .

...

class Checker
{
  public:
    Checker (int p)  {  ...  };
};

, ...

Checker checkers[2][12];

...

class Checker
{
  public:
    Checker ()  {  ...  };
    Checker (int p)  {  ...  };
};

std::vector, . - , std::vector - .

Keep your C-style array, but make it private (or at least protected) in the Council class, my advice.

0
source

Source: https://habr.com/ru/post/1730742/


All Articles