【问题标题】:Following calls to static methods with indexing when importing classes在导入类时使用索引调用静态方法
【发布时间】:2012-05-13 12:01:34
【问题描述】:

我在路径上的包文件夹+myPack 中有一个类文件myClass.m。类文件的一个简单例子是:

classdef myClass
    properties
        prop
    end

    methods
        function obj = myClass(x)
            obj.prop = x;
        end
    end
end 

现在,如果我直接调用方法并使用完整的包名访问属性,即:

x = myPack.myClass(2).prop;

正确返回x = 2。现在,如果我通过导入此类(而不是使用包名)来尝试相同的操作:

import myPack.myClass
y = myClass(2).prop

它给了我以下错误:

静态方法或构造函数调用不能被索引。 不要跟随对静态方法或构造函数的调用 任何额外的索引或点引用。

为什么这在第一种情况下有效,而在第二种情况下无效?据我了解,importing 一个类主要允许一个人使用类名而不使用长包名(以及其他考虑因素)。这两者有什么区别导致此错误,我该如何解决?

【问题讨论】:

  • 有趣。我不知道方法1有效。无论如何,方法 2 是我对 Matlab 所期望的行为,因为您通常不能对结果进行索引。包语法的好特性。

标签: oop matlab


【解决方案1】:

这对你来说更奇怪:如果你在命令窗口、脚本或函数中运行,行为会有所不同!

1) 命令提示符(第一个:ok,第二个:error)

这是你已经展示的内容

>> x = myPack.myClass(2).prop
x =
     2

>> import myPack.myClass; y = myClass(2).prop
Static method or constructor invocations cannot be indexed.
Do not follow the call to the static method or constructor with
any additional indexing or dot references. 

2) 脚本(第一个:错误,第二个:错误)

testMyClassScript.m

x = myPack.myClass(2).prop
import myPack.myClass; y = myClass(2).prop

>> testMyClassScript
Static method or constructor invocations cannot be indexed.
Do not follow the call to the static method or constructor with
any additional indexing or dot references.
Error in testMyClassScript (line 1)
x = myPack.myClass(2).prop 

(第二行也会抛出同样的错误)

3) 功能(第一个:ok,第二个:ok)

testMyClassFunction.m

function testMyClassFunction()
    x = myPack.myClass(2).prop
    import myPack.myClass; y = myClass(2).prop
end

>> testMyClassFunction
x =
     2
y =
     2

我肯定会称其为错误 :) 预期的行为是在所有情况下都给出错误。

【讨论】:

  • 这在最近的 Matlabs 中是如何工作的?我有大量使用包语法的代码,我想知道这是否是 matlab 泄漏内存的地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 2013-03-12
相关资源
最近更新 更多