如何从另一个类访问私有变量?

时间:2016-10-26 00:35:13

标签: c++ variables opengl private

我正在使用OpenGL开发一个项目,我让它以最基本的形式工作。现在,我需要做到这一点,以便我的"得到"旋转和轨道矩阵在我的Box.cpp文件中,我的速度变量是私有的,我为这些速度变量设置了函数。

我需要在main中访问这些变量,但由于它们是私有的,我显然不能。

有人能指出我正确的方向吗?

main.cpp中:

#include "vgl.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <vector>
#include "Box.h"
#include "Camera.h"
#include "VertexBufferData.h"
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>

using namespace std;
using namespace glm;

#define SPACEBAR_KEY 32
#define ESCAPE_KEY 033

Camera* camera;
vector<Box * > gameObjects;
bool keyDown[255];

void CheckKeyboard(){

    if (keyDown['a'])
        camera->RotateLeft();
    if (keyDown['d'])
        camera->RotateRight();
    if (keyDown['w'])
        camera->MoveForward();
    if (keyDown['s'])
        camera->MoveBackWard();
    if (keyDown['e'])
        camera->StrafeRight();
    if (keyDown['q'])
        camera->StrafeLeft();
}

void closeApp()
{
    delete camera;
    for (auto it = gameObjects.begin(); it != gameObjects.end(); ++it) {
        delete (*it);
    }
}


void keyboard(unsigned char key, int x, int y)
{
    switch (key) 
    {
        case ESCAPE_KEY:  // ASCII Escape Key Code
            closeApp();
            exit(EXIT_SUCCESS);
            break;
        default:
            keyDown[key] = true;
    }

    glutPostRedisplay();
}

void keyboardUp(unsigned char key, int x, int y)
{
    keyDown[key] = false;
}

void mouseWheel(int button, int direction, int x, int y)
{

    if (button == 16)
        camera->ResetFOV();
    else if (direction > 0)
        camera->ZoomIn();
    else
        camera->ZoomOut();
}

void mouseMovement(int x, int y)
{
    static bool warp = true;

    if (warp)
    {
        if (x>glutGet(GLUT_WINDOW_WIDTH) / 2)
            camera->RotateRight();
        else if (x<glutGet(GLUT_WINDOW_WIDTH) / 2)
            camera->RotateLeft();

        if (y>glutGet(GLUT_WINDOW_HEIGHT) / 2)
            camera->RotateUp();
        else if (y<glutGet(GLUT_WINDOW_HEIGHT) / 2)
            camera->RotateDown();

        glutWarpPointer(glutGet(GLUT_WINDOW_WIDTH) / 2, glutGet(GLUT_WINDOW_HEIGHT) / 2);
        warp = false;
    }
    else
        warp = true;
}

void timer(int value)
{
    glutPostRedisplay();
    glutTimerFunc(25, timer, 0);
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    CheckKeyboard();
    camera->Update();
    for (auto it = gameObjects.begin(); it != gameObjects.end(); ++it) {
        (*it)->shaderProgram->bindShader();
        glm::mat4 MVP = camera->ProjectionMatrix *  camera->ViewMatrix * (*it)->getModelMatrix();
        (*it)->shaderProgram->sendUniform4x4("MVP", glm::value_ptr(MVP));
        (*it)->Draw();
    }
    glutSwapBuffers();
}

void init()
{
    int i = 0;

    camera = new Camera();
    memset(keyDown, false, sizeof(keyDown));

    glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
    glutWarpPointer(glutGet(GLUT_WINDOW_WIDTH) / 2, glutGet(GLUT_WINDOW_HEIGHT) / 2);
    glutSetCursor(GLUT_CURSOR_FULL_CROSSHAIR);

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_CULL_FACE);

    VertexBufferData vertexBufferData = VertexBufferData("Data\\Models\\Objects.xml");

    gameObjects.push_back(new Box(vertexBufferData, glm::vec3(0.0f, 0.0f, 0.0f), "Data\\Shaders\\Vertex.shader", "Data\\Shaders\\Fragment.shader"));

    gameObjects.push_back(new Box(vertexBufferData, glm::vec3(4.0f, 0.0f, 0.0f), "Data\\Shaders\\Vertex.shader", "Data\\Shaders\\Fragment.shader"));

    gameObjects[1]->rotationSpeed = 5.0f;
    gameObjects[0]->rotationSpeed = 2.5f;
    gameObjects[1]->orbitSpeed = 1.0f;
    //gameObjects[1]->setRotation(45.0f, vec3(0.0f, 0.0f, 1.0f));
    //gameObjects[0]->setScaleMatrix(vec3(2, 2, 2));
    //gameObjects[1]->setOrbitMatrix(vec3(2.0f, 0.0f, 0.0f), 45.0f, 1, 365, 0);
}



int main(int argc, char** argv)
{
    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH);
    glutInitWindowSize(1024, 768);
    glutInitContextProfile(GLUT_CORE_PROFILE);
    glutCreateWindow("Satterwhite_Project_3");


    if (glewInit())
    {
        cerr << "Unable to init glew" << endl;
        exit(EXIT_FAILURE);
    }

    init();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutKeyboardUpFunc(keyboardUp);
    glutPassiveMotionFunc(mouseMovement);
    glutMouseWheelFunc(mouseWheel);
    glutTimerFunc(25, timer, 0);
    glutMainLoop();
    return 0;
}

Box.cpp:

#include "Box.h"

Box::Box(VertexBufferData &vbd,  vec3 initialPosition,const string vertexShader, const string fragmentShader):GameObject(vertexShader, fragmentShader)
{   
    degreesRotated = 0.0f;
    rotationSpeed = 0.0f;
    orbitSpeed = 0.0f;
    Position=initialPosition;
    vertexBufferData =vbd;

    RotationMatrix=mat4(1.0f);
    OrbitMatrix = mat4(1.0f);
    ScaleMatrix=mat4(1.0f);
    TranslationMatrix =translate(glm::mat4(1.0f), Position);

    if (!shaderProgram->initialize())
    {
        std::cerr << "Could not initialize the shaders" << std::endl;
    }

    shaderProgram->bindShader();

    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    glGenBuffers(1, &vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, vertexBufferData.verticiesSize, &vertexBufferData.verticies[0], GL_STATIC_DRAW);

    glGenBuffers(1, &fragmentBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, fragmentBuffer);
    glBufferData(GL_ARRAY_BUFFER, vertexBufferData.colorSize, &vertexBufferData.colors[0], GL_STATIC_DRAW);

    shaderProgram->linkProgram();
}
void Box::setRotation(float degrees, vec3 axis)
{
    RotationMatrix = rotate(RotationMatrix, degrees, axis);
}

void Box::setScaleMatrix(vec3 scale)
{
    ScaleMatrix = glm::scale(mat4(1.0f), scale);
}

void Box::setOrbitMatrix(float degrees, vec3 axis)
{
    OrbitMatrix = rotate(OrbitMatrix, degrees, axis);
}

void Box::Draw()
{
    shaderProgram->bindShader();

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glVertexAttribPointer(0, 3, GL_FLOAT,GL_FALSE, 0, BUFFER_OFFSET(0));

    glBindBuffer(GL_ARRAY_BUFFER, fragmentBuffer);
    glVertexAttribPointer(1, 3, GL_FLOAT,GL_FALSE, 0, BUFFER_OFFSET(0));    

    glDrawArrays(GL_TRIANGLES, 0, vertexBufferData.verticies.size());

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
}

Box.h:

#pragma once
#include "GameObject.h"

class Box :  public GameObject
{

private:
    mat4 ModelMatrix;
    mat4 RotationMatrix;
    mat4 OrbitMatrix;
    mat4 TranslationMatrix;
    mat4 ScaleMatrix;
public:
    float rotationSpeed, orbitSpeed, degreesRotated;
    void Draw();
    virtual ObjectType getType() const { return BOX; }

    mat4 getModelMatrix() {return getOrbitMatrix()*TranslationMatrix*getRotationMatrix()*ScaleMatrix;}
    mat4 getRotationMatrix()
    { 
        setRotation(rotationSpeed, vec3(0.0f, 0.0f, 1.0f));
        return RotationMatrix;
    }
    mat4 getTranslationMatrix() {return TranslationMatrix;}
    mat4 getOrbitMatrix()
    {
        setOrbitMatrix(orbitSpeed, vec3(0.0f, 0.0f, 1.0f));
        return OrbitMatrix;
    }
    mat4 getScaleMatrix() {return ScaleMatrix;}
    void setRotation(float degrees, vec3 axis);
    void setScaleMatrix(vec3 scale);
    void setOrbitMatrix(float degrees, vec3 axis);

    Box(VertexBufferData &vertexBufferData, vec3 initialPosition, const string vertexShader, const string fragmentShader);

    vec3 Position;
};

2 个答案:

答案 0 :(得分:1)

  • 如果您想从其他类访问私有成员和受保护成员,请将您想要访问目标类的私有成员和受保护成员的类声明为“朋友类”。

  • 如果你想从main或任何其他函数而不是从类中访问private和protected成员,那么声明该函数是你的类的朋友,如ostream插入运算符“&lt;&lt;”和istream提取运算符“&gt;&gt;”当你在课堂上重载它们以打印和输入你的会员数据时。

宣布一个班级或职能成为你班级的朋友就像在现实生活中结交一个你信任的新朋友,这样你就可以让他/她访问你的秘密和私人物品,这样他/她就可以帮助你实现所发现的目标如此强硬自己,但友情既不是交换也不是联想:“作为他/她你的朋友并不意味着你是他/她的朋友,因为他/她仍然可能不信任你因此不会宣称你是他的/她的朋友“,你父亲的朋友不是你的朋友。

  • 使用友谊的开销正在破坏数据隐藏和封装原则。所以经验法则是谨慎使用它。

  • 如果您希望每个人都可以访问您的私人/受保护成员,那么使用结构,其成员默认为公共范围。或者在公共范围内声明您的成员数据,这是一个非常糟糕的设计。

在这个例子中,我将向您展示如何从另一个类和另一个函数(在本例中为main函数)访问私有数据:

#include <iostream>
#include <string>
using namespace std;


class Foo; // forward declaration
class Bar; // forward declaration

class Foo
{
    public:
        Foo() : MyData(100){}

    private:
        int MyData;
        friend class Bar; // any access scope is ok. Bar will have full access to Foo
        friend int main(); // main now can access private members
};

class Bar // friend of Foo but Foo is not my Friend so it can't access mine
{
    Foo fooObj;

    public:
        Bar(){}
        void PrintFoo()const;
};

void Bar::PrintFoo()const
{
    cout << fooObj.MyData << endl; // accessing private member data of class Foo from Bar
}


int main()
{
    Foo theFoo;
    Bar theBar;
    theBar.PrintFoo();

    cout << theFoo.MyData << endl; // correct! accessing private members of foo from main because main is friend of Foo.

    return 0;
}

答案 1 :(得分:1)

如果您不想更改protected class,可以执行以下操作:

class c0    // this is some class with protected stuff and you do not want or can to change it in any way
    {
public:
    c0(){};
    ~c0(){};
protected:
    int x;
    };
class c1:c0 // this is class just to access c0 stuff without changing its source code
    {
public:
    c1(){};
    ~c1(){};
    int get_x() { return x; }
    void set_x(int new_x) { x=new_x; }
    };
void test()
    {
    c0 a;
    c1 *b=(c1*)(&a);    // access a as c1 type
    b->set_x(1);        // access protected stuff
    }

我经常使用它来访问VCL类的东西,而不以任何方式更改它(例如,以避免不必要的内存传输等)。

谨防变量和东西通常是protected有一个原因,并且通过错误的方式更改它可能会导致不可预见的问题,例如访问冲突,内存泄漏等......所以要小心你用什么改变什么?什么时间。

但这对private成员不起作用,因此对于那些需要篡改源代码以添加geters / setter或朋友的人来说@Raindrop7回答建议。