Hey, How do you access a variable in main.cpp from a class?
So if I want to get access to "board" how would I do so? -
-
main.cpp:
-
-
Boxes board[10];
-
-
Boxes.h:
-
-
void displayBox(int instance);
-
-
Boxes.cpp:
-
-
void displayBox(int instance)
-
{
-
glBegin(GL_POLYGON);
-
glColor3f(board[instance].color[0], board[instance].color[1], board[instance].color[2]); glVertex2i((int) Boxes::space + (board[instance].xPosition * (Boxes::bSize + Boxes::space)), (int) Boxes::space + (board[instance].yPosition * (Boxes::bSize + Boxes::space)));
-
glColor3f(board[instance].color[0], board[instance].color[1], board[instance].color[2]); glVertex2i((int) Boxes::space + (board[instance].xPosition * (Boxes::bSize + Boxes::space)) + Boxes::bSize, (int) Boxes::space + (board[instance].yPosition * (Boxes::bSize + Boxes::space)));
-
glColor3f(board[instance].color[0], board[instance].color[1], board[instance].color[2]); glVertex2i((int) Boxes::space + (board[instance].xPosition * (Boxes::bSize + Boxes::space)) + Boxes::bSize, (int) Boxes::space + (board[instance].yPosition * (Boxes::bSize + Boxes::space)) + Boxes::bSize);
-
glColor3f(board[instance].color[0], board[instance].color[1], board[instance].color[2]); glVertex2i((int) Boxes::space + (board[instance].xPosition * (Boxes::bSize + Boxes::space)), (int) Boxes::space + (board[instance].yPosition * (Boxes::bSize + Boxes::space)) + Boxes::bSize);
-
glEnd();
-
}
-
-
5 1405
I may not have this right but it looks like color is a property of Boxes. So I added a color property. See boxes.h below.
This is the main(); - #define _CRT_SECURE_NO_WARNINGS
-
-
#include <iostream>
-
using namespace std;
-
-
-
-
//main.cpp:
-
-
#include "Boxes.h"
-
#include "func.h"
-
-
int main()
-
{
-
-
Boxes board[10];
-
-
DisplayBox(board[3]);
-
-
}
-
The compiler will need to know about Boxes and the DisplayBox function. So there is a Boxes.h and a func.h. - // Boxes.h
-
#ifndef BOXES
-
#define BOXES
-
class Boxes
-
{
-
int color;
-
public:
-
-
void SetColor(int arg) { this->color = arg; }
-
int GetColor() { return this->color; }
-
-
-
-
};
-
#endif
-
-
//func.h
-
-
#ifndef FUNCH
-
#define FUNCH
-
-
#include "Boxes.h"
-
void DisplayBox(Boxes& arg);
-
-
#endif
-
Finally the functions are in their own file but here the compiler needs to know about Boxes: - // func.cpp
-
#include <iostream>
-
using namespace std;
-
-
#include "Boxes.h"
-
-
void DisplayBox(Boxes& arg)
-
{
-
cout << arg.GetColor();
-
}
Is this what you had in mind?
Oralloy 988
Recognized Expert Contributor
You can just write this into boxes.cpp
Didn't work Oralloy.
Sorry, I forgot to add "float color[3] = {1.0f, 1.0f, 1.0f};" to Boxes.h. I just moved the functions I needed "board[]" in to the "main.cpp" file. Here is my entire code with a separate problem...
In this project I make a window with some squares. When you click on one of these squares it should toggle it's color. BUT for some reason it wont change color, but it registered and found out that I clicked on it...
My guess is that it's an instance flaw or "color[3]" (in Boxes.h) is a global value, which it shouldn't be because it isn't static.
What is causing this flaw?
main.cpp: -
#include <windows.h>
-
#include <gl/gl.h>
-
#include "Boxes.h"
-
-
LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);
-
void EnableOpenGL(HWND hwnd, HDC*, HGLRC*);
-
void DisableOpenGL(HWND, HDC, HGLRC);
-
-
const int wWidth = 1080 + Boxes::space;
-
const int wHeight = 724 + Boxes::space;
-
const int nrBoxX = 2; //max = 45
-
const int nrBoxY = 2; //max = 30
-
const int nrBoxT = 4; //max = 1350
-
Boxes board[4];
-
POINT mousePt;
-
int mouseX = 0;
-
int mouseY = 0;
-
bool isBoxesSetup = false;
-
-
void setupBox()
-
{
-
int a = 0;
-
for (int y = 0; y < nrBoxY; y++)
-
{
-
for (int x = 0; x < nrBoxX; x++)
-
{
-
board[a].xPosition = x;
-
board[a].yPosition = y;
-
a++;
-
}
-
}
-
isBoxesSetup = true;
-
}
-
-
void displayBox(int instance)
-
{
-
glBegin(GL_POLYGON);
-
glColor3f(board[instance].color[0], board[instance].color[1], board[instance].color[2]); glVertex2i((int) Boxes::space + (board[instance].xPosition * (Boxes::bSize + Boxes::space)), (int) Boxes::space + (board[instance].yPosition * (Boxes::bSize + Boxes::space)));
-
glColor3f(board[instance].color[0], board[instance].color[1], board[instance].color[2]); glVertex2i((int) Boxes::space + (board[instance].xPosition * (Boxes::bSize + Boxes::space)) + Boxes::bSize, (int) Boxes::space + (board[instance].yPosition * (Boxes::bSize + Boxes::space)));
-
glColor3f(board[instance].color[0], board[instance].color[1], board[instance].color[2]); glVertex2i((int) Boxes::space + (board[instance].xPosition * (Boxes::bSize + Boxes::space)) + Boxes::bSize, (int) Boxes::space + (board[instance].yPosition * (Boxes::bSize + Boxes::space)) + Boxes::bSize);
-
glColor3f(board[instance].color[0], board[instance].color[1], board[instance].color[2]); glVertex2i((int) Boxes::space + (board[instance].xPosition * (Boxes::bSize + Boxes::space)), (int) Boxes::space + (board[instance].yPosition * (Boxes::bSize + Boxes::space)) + Boxes::bSize);
-
glEnd();
-
}
-
-
int WINAPI WinMain(HINSTANCE hInstance,
-
HINSTANCE hPrevInstance,
-
LPSTR lpCmdLine,
-
int nCmdShow)
-
{
-
WNDCLASSEX wcex;
-
HWND hwnd;
-
HDC hDC;
-
HGLRC hRC;
-
MSG msg;
-
BOOL bQuit = FALSE;
-
-
/* register main window class */
-
wcex.cbSize = sizeof(WNDCLASSEX);
-
wcex.style = CS_OWNDC;
-
wcex.lpfnWndProc = WindowProc;
-
wcex.cbClsExtra = 0;
-
wcex.cbWndExtra = 0;
-
wcex.hInstance = hInstance;
-
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
-
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
-
wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
-
wcex.lpszMenuName = NULL;
-
wcex.lpszClassName = "All White";
-
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
-
-
-
if (!RegisterClassEx(&wcex))
-
return 0;
-
-
/* create main window */
-
hwnd = CreateWindowEx(0,
-
"All White",
-
"All White",
-
WS_OVERLAPPEDWINDOW,
-
CW_USEDEFAULT,
-
CW_USEDEFAULT,
-
wWidth,
-
wHeight,
-
NULL,
-
NULL,
-
hInstance,
-
NULL);
-
-
ShowWindow(hwnd, nCmdShow);
-
-
/* enable OpenGL for the window */
-
EnableOpenGL(hwnd, &hDC, &hRC);
-
-
/* program main loop */
-
while (!bQuit)
-
{
-
/* check for messages */
-
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
-
{
-
/* handle or dispatch messages */
-
if (msg.message == WM_QUIT)
-
{
-
bQuit = TRUE;
-
}
-
else
-
{
-
TranslateMessage(&msg);
-
DispatchMessage(&msg);
-
}
-
}
-
else
-
{
-
/* OpenGL animation code goes here */
-
-
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
-
glClear(GL_COLOR_BUFFER_BIT);
-
-
glPushMatrix();
-
-
glOrtho(0, wWidth, wHeight, 0, -1, 1);
-
-
if (!isBoxesSetup) setupBox();
-
-
for (int a = 0; a < nrBoxT; a++)
-
{
-
displayBox(a);
-
}
-
-
glPopMatrix();
-
-
SwapBuffers(hDC);
-
}
-
}
-
-
/* shutdown OpenGL */
-
DisableOpenGL(hwnd, hDC, hRC);
-
-
/* destroy the window explicitly */
-
DestroyWindow(hwnd);
-
-
return msg.wParam;
-
}
-
-
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
-
{
-
switch (uMsg)
-
{
-
case WM_CLOSE:
-
PostQuitMessage(0);
-
break;
-
-
case WM_DESTROY:
-
return 0;
-
break;
-
-
case WM_LBUTTONDOWN:
-
GetCursorPos(&mousePt);
-
ScreenToClient(hwnd, &mousePt);
-
mouseX = mousePt.x;
-
mouseY = mousePt.y;
-
for (int i = 0; i < nrBoxT; i++)
-
{
-
bool buttonPressed = board[i].checkIfPressed(mouseX, mouseY);
-
if (board[i].checkIfPressed(mouseX, mouseY))
-
{
-
board[i].toggleColorState(i);
-
}
-
}
-
break;
-
-
case WM_KEYDOWN:
-
{
-
switch (wParam)
-
{
-
case VK_ESCAPE:
-
PostQuitMessage(0);
-
break;
-
-
case VK_SPACE:
-
PostQuitMessage(0);
-
break;
-
}
-
}
-
break;
-
-
default:
-
return DefWindowProc(hwnd, uMsg, wParam, lParam);
-
}
-
-
return 0;
-
}
-
-
void EnableOpenGL(HWND hwnd, HDC* hDC, HGLRC* hRC)
-
{
-
PIXELFORMATDESCRIPTOR pfd;
-
-
int iFormat;
-
-
/* get the device context (DC) */
-
*hDC = GetDC(hwnd);
-
-
/* set the pixel format for the DC */
-
ZeroMemory(&pfd, sizeof(pfd));
-
-
pfd.nSize = sizeof(pfd);
-
pfd.nVersion = 1;
-
pfd.dwFlags = PFD_DRAW_TO_WINDOW |
-
PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
-
pfd.iPixelType = PFD_TYPE_RGBA;
-
pfd.cColorBits = 24;
-
pfd.cDepthBits = 16;
-
pfd.iLayerType = PFD_MAIN_PLANE;
-
-
iFormat = ChoosePixelFormat(*hDC, &pfd);
-
-
SetPixelFormat(*hDC, iFormat, &pfd);
-
-
/* create and enable the render context (RC) */
-
*hRC = wglCreateContext(*hDC);
-
-
wglMakeCurrent(*hDC, *hRC);
-
}
-
-
void DisableOpenGL (HWND hwnd, HDC hDC, HGLRC hRC)
-
{
-
wglMakeCurrent(NULL, NULL);
-
wglDeleteContext(hRC);
-
ReleaseDC(hwnd, hDC);
-
}
-
Boxes.h: -
#ifndef BOXES_H
-
#define BOXES_H
-
-
class Boxes
-
{
-
public:
-
float color[3] = {1.0f, 1.0f, 1.0f};
-
const static int space = 4;
-
const static int bSize = 20;
-
int xPosition = 0;
-
int yPosition = 0;
-
int realMinX = (int) space + (xPosition * (bSize + space));
-
int realMaxX = (int) space + (xPosition * (bSize + space)) + bSize;
-
int realMinY = (int) space + (yPosition * (bSize + space));
-
int realMaxY = (int) space + (yPosition * (bSize + space)) + bSize;
-
int cState = 3;
-
int nState = 0;
-
-
Box(int xPos, int yPos);
-
float getColor();
-
void setColor(float red, float green, float blue);
-
void toggleColorState(int i);
-
bool checkIfPressed(int x, int y);
-
-
protected:
-
-
private:
-
-
};
-
-
#endif // BOXES_H
-
-
Boxes.cpp: -
#include "Boxes.h"
-
#include <windows.h>
-
#include <gl/gl.h>
-
-
extern Boxes board[4];
-
-
Boxes::Box(int xPos, int yPos)
-
{
-
xPosition = xPos;
-
yPosition = yPos;
-
}
-
-
void Boxes::toggleColorState(int i)
-
{
-
cState = nState;
-
nState++;
-
if (nState > 3) nState = 0;
-
-
if (cState == 0)
-
{
-
board[i].color[0] = 1.0f;
-
board[i].color[1] = 0.0f;
-
board[i].color[2] = 0.0f;
-
}
-
if (cState == 1)
-
{
-
board[i].color[0] = 0.0f;
-
board[i].color[1] = 1.0f;
-
board[i].color[2] = 0.0f;
-
}
-
if (cState == 2)
-
{
-
board[i].color[0] = 0.0f;
-
board[i].color[1] = 0.0f;
-
board[i].color[2] = 1.0f;
-
}
-
if (cState == 3)
-
{
-
board[i].color[0] = 1.0f;
-
board[i].color[1] = 1.0f;
-
board[i].color[2] = 1.0f;
-
}
-
}
-
-
//Not used
-
float Boxes::getColor()
-
{
-
return *color;
-
}
-
-
//Not used
-
void Boxes::setColor(float red, float green, float blue)
-
{
-
color[0] = red;
-
color[1] = green;
-
color[2] = blue;
-
}
-
-
bool Boxes::checkIfPressed(int x, int y)
-
{
-
if (x > realMinX && x < realMaxX && y > realMinY && y < realMaxY) return true;
-
return false;
-
}
-
-
You cannot put any code in a header file that creates variables or that is code for the body of a function. Every time the .h is included by the various .cpp files you get another set of variables. Then your build dies in the link with redefinition errors.
Instead use a #define in your include: - #define RED 1.0
-
#define BLUE 2.0
-
There should never be any hard-coded symbolic constants in your code. A symbolic constant is like 4 or 25.2, etc...
What is this????? - void Boxes::toggleColorState(int i)
-
14. {
-
15. cState = nState;
-
16. nState++;
-
17. if (nState > 3) nState = 0;
-
18.
-
19. if (cState == 0)
-
20. {
-
21. board[i].color[0] = 1.0f;
-
22. board[i].color[1] = 0.0f;
-
23. board[i].color[2] = 0.0f;
-
24. }
-
This is class member function. There is no board variable possible. board is an array in main(). There is no variable i The code I sent you uses board only in main().
Also, your class should have no public data members. This is not a C struct but a C++ class. Any color values should be defined in the header file as above, or you will need a Color class that has a private obj in Boxes.
Remember, all the processing is in main(). All the class member functions do is manage the private data members of the class.
It looks like you are merging the application code with the class code and this will never work. - main.cpp:
-
-
Boxes board[10];
-
-
board[1].setColor(etc...};
This code changes the Boxes object board[1]. Inside the member function all you have is the address of the board object which is calling the member function. Read up on the this pointer.
keep posting . We have all gone through this.
donbock 2,426
Recognized Expert Top Contributor
It isn't that you can't put variable or function definitions in a header file -- it's that it is almost always a mistake to do so. Sometimes doing so triggers a build error, other times it may yield a possibly intermittent run-time bug.
Typically, you put a variable or function definition in one .c/.cpp file and the corresponding declaration in a header file that is included by all .c/.cpp files that define or refer to that variable or function.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Hal Vaughan |
last post by:
If I have a class like this:
public class Tester {
ObjectType1 ot1;
ObjectType2 ot2;
ObjectType3 ot3;
public void main(String args) {
//Preliminary checking, resulting in bRun being
|
by: dberlin |
last post by:
hey,
My situation is like this-
whenever I create an application with a gui I put the gui source in one
file that calls all the other classes (from imported modules).
This creates a problem when needing to print something out on a gui
control or something similar. It is then needed to send the called
class the control object and the class will then modify it on its part.
This makes the classes I create not very generic, and just gives me...
|
by: diadia |
last post by:
when i write two classes as follow .
compiler tell me that i can't access private number from other class
but if types of two classes are the same it don't have error message ? why?
class schema
{
private:
|
by: Barbara |
last post by:
Is it possible in C# to merge two strings to access variable?
(Like in JScript: document('variable'+200).style...)
What I am trying to do is:
I have a class Structure.cs
I would like to create several Structure-s, fill their elements with data,
but in a way that
I can choose starting number (sometimes I need Structure,,
sometimes )
|
by: Ian Meakin |
last post by:
I have a page called admin.aspx and it uses admin.aspx.cs as it's code behind
file.
When developing the application on my localhost using VS.NET i reference
thsi file using codebehind="admin.aspx.cs". I now have to upload it to a
production server which i have no control over and has no bin directory (and
i cannot create one) to place the project dll assemblies in to.
I have now changed the file to use the src attricbute so the files...
| |
by: STom |
last post by:
I have a class declare like this:
<Serializable>Public Class Talk
Public Structure _localTalk
Public _iTalkNumber as Integer
End structure
End Class
I can see the structure from other classes, but I cannot see the internal
|
by: Scott Starker |
last post by:
Is there anyway to do this?
Every time any button is click inside class Form1, MyButtomArray.CharArray
(MyButtomArray is a class) gets set (or reset) (bool). Once this is done the
class TEC gets executed. I want to access MyButtonArray.CharArray to get the
bool values in TEC.
Any ideas?
Scott
|
by: Guillaume BRAUX |
last post by:
Hello,
I am looking for a way to create a method that will be available to other
classes in my project, but without needing to instanciate the class.
I don't want this method to be static (il would be too easy ^^) !
Finally, i'd like to call my method by only doing "methodClass.myClass()"
without having to instanciate "methodClass" before (like form1.ActiveForm or
Form1.DefaultFont that do not need to instanciate form1 to use them ...).
|
by: Chris Zopers |
last post by:
Hello,
I have two UserControls on a aspx page. I need to read a property of the
first UserControl from within the second UserControl. The UserControls
only know about themselves, so I can't declare a variable of the other
usercontrol's type. So I can't do something like this in the second
UserControl:
FirstUserControl first =
(FirstUserControl)this.Parent.FindControl("FirstUserControl")
|
by: AlarV |
last post by:
I want to create an array of pointers, for my class. Each pointer will in fact be the 'head' of a dynamic list. I don't know the size of the array and it has to be given by the user.
So my problem is that in my class I have to read the size in the constructor. In the other functions of the class( e.g. insert etc.) the table has to EXIST. However, when I try to access it from the other functions (e.g. insert) the table isn't NULL. And the...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |