-2

嗨,我使用 DirectX 在 C++ 中制作游戏

但我也有游戏的控制台版本(使用“X”和其他字符来表示事物)

我有以下代码:

Unit::Unit(UnitType u){
    ZeroAll();                        // function that zeros all variables
    this->operator=(fileToUnit(u));   // error making code
}

UnitType 是一个简单的枚举数据类型,具有三个值 {Infantry , Alien , Predator}。

Operator函数定义如下

Unit operator= (Unit u) { return u; }

fileToUnit 是...

Unit fileToUnit(UnitType u);

只是制作一个临时单元并返回它。我真的不知道该怎么做,但我需要从构造函数中更改整个类。

编辑:抱歉这么不具体

我的问题是:如何让一个类根据函数的结果改变它的值

this = functionReturningSameDataType( DataType ConstructorParameters );

错误如下

Microsoft Visual C++ Runtime Library

Debug Assertion Failed!

Program: C:\Windows\system32\MSVCP110D.dll
File: C:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring
Line: 1143

Expression: invalid null pointer

For Information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

(Press Retry to Debug the application)
4

1 回答 1

0

如果我正确理解您的问题,您有一个以 a作为参数的自由函数,以某种可能基于实例的方式构造 a ,然后将其返回给构造函数。UnitTypeUnitUnitTypeUnit::Unit(UnitType)

我不确定我是否完全理解Unit fileToUnit(UnitType u)在这种情况下的目的。为什么它是免费功能?使其成为成员函数并从构造函数中调用它:

class Unit
{
private:
   // Example data members
   int foo;
   int bar;
public:
   Unit(UnitType u)
   {
      fileToUnit(UnitType u);
   };
private:
   void fileToUnit(UnitType u)
   {
       // Set data members here
       foo = 1;
       bar = 1;
   };
};

编辑:在我这样一个简化的例子中,fileToUnit根本不需要存在,代码应该直接在构造函数中:

class Unit
{
private:
   // Example data members
   int foo;
   int bar;
public:
   Unit(UnitType u)
   {
      // Set foo and bar here, using whatever
      // information you need from u
   };
};
于 2013-03-18T23:03:42.367 回答