可变方法 X.this 不可使用 D 中的不可变对象错误调用
mutable method X.this is not callable using a immutable object error in D
我从这个页面复制了这个 D 代码:http://ddili.org/ders/d.en/class.html
import std.stdio;
struct S {
this (int x) {
this.x = x;
}
int x;
}
class Foo
{
S o;
char[] s;
int i;
// ...
this(S o, const char[] s, int i)
{
this.o = o;
this.s = s.dup;
this.i = i;
}
Foo dup() const
{
return new Foo(o, s, i);
}
immutable(Foo) idup() const
{
return new immutable(Foo)(this.o, this.s, this.i);
}
}
void main()
{
auto var1 = new Foo(S(5), "hello", 42);
auto var2 = var1.dup();
immutable(Foo) imm = var1.idup();
writeln(var1);
writeln(var2);
writeln(imm);
}
问题是我在编译时出现 "mutable method a.Foo.this is not callable using a immutable object" 错误。
您收到此错误是因为您调用了 new immutable(Foo)(this.o, this.s, this.i);
这会查找 immutable
构造函数,而您只定义了可变对象的构造函数,这是默认设置。您可以通过编写构造函数并将其标记为 immutable
来解决此问题,就像将方法标记为 const
一样,但还有更好且通常更简单的解决方案。
如果可以,请尝试将您的构造函数和方法标记为 pure
。如果将构造函数标记为 pure
,则构造函数可用于可变对象和 immutable
对象。或者,您可以将 idup
方法标记为 pure
,构造一个 new Foo
,这是一个可变对象,并将其 return 标记为 immutable
。这都是因为 pure
如果数据 returned 未在其他地方引用,函数可以安全地创建不可变数据。换句话说,唯一拥有的内存可以移出 immutable
类型。
我从这个页面复制了这个 D 代码:http://ddili.org/ders/d.en/class.html
import std.stdio;
struct S {
this (int x) {
this.x = x;
}
int x;
}
class Foo
{
S o;
char[] s;
int i;
// ...
this(S o, const char[] s, int i)
{
this.o = o;
this.s = s.dup;
this.i = i;
}
Foo dup() const
{
return new Foo(o, s, i);
}
immutable(Foo) idup() const
{
return new immutable(Foo)(this.o, this.s, this.i);
}
}
void main()
{
auto var1 = new Foo(S(5), "hello", 42);
auto var2 = var1.dup();
immutable(Foo) imm = var1.idup();
writeln(var1);
writeln(var2);
writeln(imm);
}
问题是我在编译时出现 "mutable method a.Foo.this is not callable using a immutable object" 错误。
您收到此错误是因为您调用了 new immutable(Foo)(this.o, this.s, this.i);
这会查找 immutable
构造函数,而您只定义了可变对象的构造函数,这是默认设置。您可以通过编写构造函数并将其标记为 immutable
来解决此问题,就像将方法标记为 const
一样,但还有更好且通常更简单的解决方案。
如果可以,请尝试将您的构造函数和方法标记为 pure
。如果将构造函数标记为 pure
,则构造函数可用于可变对象和 immutable
对象。或者,您可以将 idup
方法标记为 pure
,构造一个 new Foo
,这是一个可变对象,并将其 return 标记为 immutable
。这都是因为 pure
如果数据 returned 未在其他地方引用,函数可以安全地创建不可变数据。换句话说,唯一拥有的内存可以移出 immutable
类型。