初始化列表中的引用

时间:2011-10-14 13:20:17

标签: c++

我有一个带有两个参考变量的相机类。我想通过构造函数传递两个引用并将引用变量分配给它们,这样如果我在这个类中更改它们,我之前定义的(并传入)的其他引用也会改变。但是,我收到错误:

a reference of type "D3DXMATRIX &" (not const-qualified) cannot be initialized with a value of type "D3DMATRIX"

error C2440: 'initializing' : cannot convert from 'D3DMATRIX' to 'D3DXMATRIX &'

这是我的代码:

头:

#ifndef CAMERA_H
#define CAMERA_H

#include <d3d10.h>
#include <d3dx10.h>   
#include "globals.h"
#include "direct3D.h"

class Camera
{
private:
D3DXMATRIX &matProjection, &matView;
public:
Camera(
    float fOVDeg, float nearCull, float farCull,
    float xPos, float yPos, float zPos,
    D3DMATRIX &matProjection, D3DMATRIX &matView);
void SetCamera(float fOVDeg, float nearCull, float farCull);
void AdjustCamera(float x, float y, float z);
};

#endif

源:

#include "Camera.h"

Camera::Camera(
float fOVDeg, float nearCull, float farCull,
float xPos, float yPos, float zPos,
D3DMATRIX &matProjection, D3DMATRIX &matView) 
: matProjection(matProjection), matView(matView)
{
this->SetCamera(fOVDeg, nearCull, farCull);
this->AdjustCamera(xPos, yPos, zPos);
}

// Set the fixed properties of the 3D camera
void Camera::SetCamera(float fOVDeg, float nearCull, float farCull)
{
// create a projection matrix
D3DXMatrixPerspectiveFovLH(
    &matProjection,
    (float)D3DXToRadian(fOVDeg),    // the horizontal field of view
    (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, // aspect ratio
    nearCull,    // the near view-plane
    farCull);    // the far view-plane
}

// Set the adjustable properties of the 3D camera
void Camera::AdjustCamera(float x, float y, float z)
{
D3DXMatrixLookAtLH(&matView,
                   &D3DXVECTOR3 (x, y, z),
                   &D3DXVECTOR3 (0.0f, 0.0f, 0.0f),
                   &D3DXVECTOR3 (0.0f, 1.0f, 0.0f));
}

显然我误解了一些基本的东西。任何帮助将不胜感激!

我得到的错误在构造函数的初始化列表中。

这是我实例化相机的地方:

Camera* camera;
D3DMATRIX matProjection, matView;

//called once
void Initialise(HWND hWnd)
{
initD3D(hWnd);
    init_pipeline();
cube = new Cube();

level = new Level(*cube);

camera = new Camera(
    45.0f, 1.0f, 10000.0f,
    0.0f, 9.0f, 100.0f,
    matProjection, matView);

test = 0.0f;
}

3 个答案:

答案 0 :(得分:3)

在我看来,您正尝试使用对Base的引用初始化对Derived的引用,如:

class D3DMATRIX {};
class D3DXMATRIX : public D3DMATRIX {};

class Camera {
private:
    D3DXMATRIX& m_;

public:
    Camera(D3DMATRIX& m) : m_(m) {}
};

MSVC9.0说:

test.cpp(9) : error C2440: 'initializing' : cannot convert from 'D3DMATRIX' to 'D3DXMATRIX &'

也许你应该让Camera构造函数使用D3DXMATRIX&amp;作为参数?

答案 1 :(得分:2)

问题是D3DXMATRIX派生自D3DMATRIX。您不能将对D3DMATRIX的引用存储为D3DXMATRIX。

因此,要么首先传入D3DXMATRIX,要么存储D3DMATRIX。这是一个不起作用的简单例子:

class A
{

};

class B : public A
{

};

class C
{
public:

    C(A& a) : MyB(a) {}

private:

    B& MyB;
};

答案 2 :(得分:1)

您没有告诉我们您实例化Camera或任何行号的位置。

但是你可能试图将临时绑定到构造函数中的那些非const引用参数。

为什么不存储const D3DXMATRIX&,或者复制。

相关问题