locked
Trouble Declaring a Global Struct Object RRS feed

  • Question

  • Hello,

    I'm trying to use a struct in my program, and I need to declare an object of that struct outside any functions. So it looks a little like this:

    #include <iostream> 
     
    using namespace std; 
     
    struct Object 
         float x; 
         float y; 
         float z; 
    }; 
     
    Object box; 
     
    box.x = 0.0f; 
    box.y = 0.0f; 
    box.z = 0.0f; 
     
    void MoveObject(Object object) 
         object.x += 20.0; 
     
     
    int main() 
         int choice;      
     
         cout << "Would you like to move the box?(1/0)"; 
         cin >> choice; 
     
         if(choice == 1) 
         { 
              MoveObject(box); 
         } 
     
         return 0; 
     
     

    What's happening, though, is that I get errors telling be about how I should put a ';' before the '.' in the line "box.x = 0.0f;" when I try to compile the script. I've put the 'Object box' declaration and all related lines inside 'int main()' and it works fine, but I really need a way to be able to declare a global struct object.

    Thanks for your help


    Tuesday, September 30, 2008 8:58 PM

Answers

  • You can't put code outside of the body of a function or a class. How would it execute? It's simply illegal C++.

    On the other hand, it is perfectly ok to use a constructor in your struct for initialization purposes, as in:

    struct Object 
         float x; 
         float y; 
         float z; 
        Object ()
        {
            x = 0.0f; y = 0.0f; z = 0.0f;
        }
    };
    • Marked as answer by Lil_Ozzy Tuesday, September 30, 2008 9:16 PM
    Tuesday, September 30, 2008 9:05 PM
  • To add to what Brian said, you should pass your object by reference:

    void MoveObject(Object& object)
    {
         object.x += 20.0;
    }


    David Wilkinson | Visual C++ MVP
    • Marked as answer by Lil_Ozzy Wednesday, October 1, 2008 6:04 PM
    Tuesday, September 30, 2008 9:30 PM

All replies

  • You can't put code outside of the body of a function or a class. How would it execute? It's simply illegal C++.

    On the other hand, it is perfectly ok to use a constructor in your struct for initialization purposes, as in:

    struct Object 
         float x; 
         float y; 
         float z; 
        Object ()
        {
            x = 0.0f; y = 0.0f; z = 0.0f;
        }
    };
    • Marked as answer by Lil_Ozzy Tuesday, September 30, 2008 9:16 PM
    Tuesday, September 30, 2008 9:05 PM
  • To add to what Brian said, you should pass your object by reference:

    void MoveObject(Object& object)
    {
         object.x += 20.0;
    }


    David Wilkinson | Visual C++ MVP
    • Marked as answer by Lil_Ozzy Wednesday, October 1, 2008 6:04 PM
    Tuesday, September 30, 2008 9:30 PM