编译器无法识别实现文件中的 class 成员函数类型,但可在接口文件中识别

Compiler not recognising class member function type in implementation file but recognised in interface file

作为我创建的 class 的一部分,我有一个表示常量缓冲区的结构。在接口文件(.h 文件)中有一个 getter 函数,其 return 类型与结构的类型相同。 .h 文件中的函数原型被编译器识别得很好,但是在函数定义的实现文件(.cpp 文件)中,编译器在函数的 return 类型下面用红色下划线,表示它是不明确的。头文件包含在 .cpp 文件中,因此我不确定为什么无法识别 return 类型的函数。这是代码:

对于头文件:

#ifndef _PLAYERCLASS_H_
#define _PLAYERCLASS_H_

//Std library includes
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <math.h>
#include <vector>
#include <memory>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dx10.h>

// include the Direct3D Library file
#pragma comment (lib, "d3d11.lib")
#pragma comment (lib, "d3dx11.lib")
#pragma comment (lib, "d3dx10.lib")

class PlayerClass
{
private:

// a struct to define the constant buffer
struct CBUFFER
{
    D3DXMATRIX Final;
    D3DXMATRIX Rotation;
    D3DXVECTOR4 LightVector;
    D3DXCOLOR LightColor;
    D3DXCOLOR AmbientColor;
};

public:

//Functions
PlayerClass();        //Constructor
~PlayerClass();       //Destructor

//Functions to set up player

//Getters
CBUFFER constBuff();                    //Return the constant buffer 

//Setters



private:

//Some private member variables

//Constant buffer to contain alterations to player etc
CBUFFER pUpdates;


};

#endif

对于 .cpp 文件:

#include "Player.h"
#include <Windows.h>
PlayerClass::PlayerClass()
{
    pUpdates.LightVector = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 0.0f);
    pUpdates.LightColor = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f);
    pUpdates.AmbientColor = D3DXCOLOR(0.6f, 0.6f, 0.6f, 1.0f);

}

PlayerClass::~PlayerClass()
{

}

void PlayerClass::initPlayer()
{

}

CBUFFER PlayerClass::constBuff()
{
    return pUpdates;
}

未被识别的函数是最后一个函数,特别是红色下划线的 CBUFFER 部分。

名称 CBUFFERPLayerClass 的范围内。使用像您的

这样的老式 C++03 函数定义
CBUFFER PlayerClass::constBuff()
{
    return pUpdates;
}

在封闭的命名空间中查找名称 CBUFFER,但未找到。

你可以玩资格赛,比如

PlayerClass::CBUFFER PlayerClass::constBuff()
{
    return pUpdates;
}

或者,(IMO) 聪明一点,对所有函数定义采用一种更容易理解的语法,然后写

auto PlayerClass::constBuff()
    -> CBUFFER
{
    return pUpdates;
}

其中,当遇到 CBUFFER 名称时,编译器知道它在成员函数定义中,因此也在 class.

中查找该名称

在其他新闻中,class CPlayer 等名称前缀和 PlayerClass 等后缀不添加任何相关信息。他们只会增加更多的写作和更多的阅读。那么为什么不命名 class Player。此外,ALL UPPERCASE 很碍眼,并且与宏的通用命名约定(以及常量的 Java/Python 约定)冲突。那么为什么不称之为例如Buffer – 或者更能自我描述的东西,也许。