dlang语言dmd2编译器中编译以下代码报错this is only defined in non-static member functions not main请帮我纠正代码如下import stdstdio;void main int a = 1; int b = 2; 使用mixin生成一个函数将a和b相加并返回结果 mixinint sumint a
这个错误是因为 this 是在类的非静态成员函数中定义的,而 main 不是类的成员函数。因此,你需要将 mixin 和 __traits 的使用放在一个类的非静态成员函数中。下面是一个简单的示例:
import std.stdio;
class MyClass { int sum(int a, int b) { return a + b; } }
void main() { int a = 1; int b = 2;
MyClass myClass = new MyClass();
auto sumFunc = __traits(getMember, typeof(myClass), "sum");
int result = sumFunc(myClass, a, b);
writeln("The sum of ", a, " and ", b, " is ", result);
}
在这个示例中,我们创建了一个名为 MyClass 的类,并在其中定义了一个名为 sum 的非静态成员函数。然后在 main 函数中,我们实例化了这个类,并使用 __traits 获取了 sum 函数的函数指针,并调用它来计算 a 和 b 的和
原文地址: https://www.cveoy.top/t/topic/e4QQ 著作权归作者所有。请勿转载和采集!