C2512 使用 ref 类时出错



这绝对是一个经常出现的版本 - 但我认为这个版本有点不同。我在代码中收到以下错误error C2512: 'DataTypes::DateTime': no appropriate default constructor available.此错误最近在从 .NET 2 升级到 期间出现。NET4.6

本质上,我们有一个如下所示的引用类:

public ref class DateTime : DataType {
public:
DateTime();
//just highlighting that the constructor is available in the class and hasn't been missed
}

此类继承自具有静态构造函数的接口DataType- 如下所示:

public interface class DataType {
static DataType() {
}
}

然后这一切都被捆绑在另一个类中,这是我们得到错误的地方

public ref class DateCounter {
static DateTime dateTime;
}

现在 - 我已经设法通过以下方式修复了错误

public ref class DateCounter {
static DateTime dateTime = new DateTime();
}

这似乎是在强行告诉它使用这个构造函数 - 但由于这种设置在应用程序中被大量使用,因此遍历所有这些并修改它们是一项艰巨的工作。

我只是想知道是否有人知道一个更优雅的解决方案,或者至少可以给出一个原因,为什么它会在两个版本的 .NET 之间发生变化

编辑- 所以我建立了一个小项目,看起来它在做同样的事情。项目中有三个文件 - TestClass.h:

public ref class TestClass : TestInterface {
protected:
static int staticItem = 0;
int holdInt;
public:
virtual void Clear();
TestClass();
static TestClass();
TestClass(int takeIn);
TestClass(TestClass% value);
TestClass% operator= (TestClass% input);
};

TestClassMethods.h:

TestClass::TestClass() {
}
TestClass::TestClass(int takeIn) {
this->holdInt = takeIn;
}
TestClass::TestClass(TestClass% value) {
*this = value;
}
void TestClass::Clear() {
this->holdInt = 0;
}
TestClass% TestClass::operator= (TestClass% toAssign) {
this->holdInt = toAssign.holdInt;
return *this;
}

和类库1.cpp

namespace TestNamespace {
ref class TestClass;
public interface class TestInterface {
void Clear();
};
public ref class Counter {
static TestClass counterVariable;
};
}

这些复制了代码定义在我正在处理的应用程序中的设置方式,并且应该会产生有问题的问题

我认为这里的问题是你调用了 DateTime 的默认(无参数(析构函数,这是一种值类型。值类型的默认构造函数是隐式定义的,并将此类型的实例设置为其默认值。

因此,要摆脱此错误消息,最简单的解决方法是使用参数化构造函数之一,例如"new DateTime (0(",它产生与默认构造函数相同的值。另一个值得尝试的选项是使用 C++/CLI 的特殊"堆栈语义"语法,它透明地完成所有构建/销毁工作。为此,请像局部C++变量一样声明 DateTime 实例:

DateTime vDateTime;

请注意,在这种情况下不得指定空括号。C++编译器会将此识别为默认构造函数调用。参数化声明将如下所示 - 现在带有所需的括号:

DateTime vDateTime (0);

最新更新