Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't this c++ code compile?

Tags:

c++

visual-c++

Seeig that i'm new to C++ I thought i'd try and write a very simple console app that populates a 2D-array and displays its contents.

But the code I've written won't compile.

Some of the errors I get are:

error C2065: 'box' : undeclared identifier
error C2228: left of '.GenerateBox' must have class/struct/union

Here is my code:

#include <iostream>
using namespace std;

int main()
{
  Box box;
  box.GenerateBox();
}

class Box
{
private:
  static int const maxWidth = 135;
  static int const maxHeight = 60; 
  char arrTest[maxWidth][maxHeight];

public:
    void GenerateBox()
    {
      for (int i=0; i<maxHeight; i++)
        for (int k=0; k<maxWidth; k++)
        {
          arrTest[i][k] = 'x';
        }

      for (int i=0; i<maxHeight; i++)
      {
        for (int k=0; k<maxWidth; k++)
        {
          cout << arrTest[i][k];
        }
           cout << "\n";
      }
    }
};

Any idea whats causing these errors?

like image 311
Draco Avatar asked Nov 30 '22 16:11

Draco


1 Answers

The C++ compiler reads source files in a single pass, from top to bottom. You have described the Box class at the bottom, after main(), after the part where you attempt to use the class. Accordingly, when the compiler gets to the part where you say 'Box box;', it has not yet seen the class definition, and thus has no idea what 'Box' means.

like image 84
Karl Knechtel Avatar answered Dec 05 '22 06:12

Karl Knechtel