我有一个容纳数据的容器类.创建容器时,有不同的方法来传递数据.
在Java中,我将创建三个构造函数.以下是在Python中可能出现的情况:
class Container:
    def __init__(self):
        self.timestamp = 0
        self.data = []
        self.metadata = {}
    def __init__(self, file):
        f = file.open()
        self.timestamp = f.get_timestamp()
        self.data = f.get_data()
        self.metadata = f.get_metadata()
    def __init__(self, timestamp, data, metadata):
        self.timestamp = timestamp
        self.data = data
        self.metadata = metadata
在Python中,我看到了三个明显的解决方案,但它们都不是很漂亮:
答:使用关键字参数:
def __init__(self, **kwargs):
    if 'file' in kwargs:
        ...
    elif 'timestamp' in kwargs and 'data' in kwargs and 'metadata' in kwargs:
        ...
    else:
        ... create empty container
B:使用默认参数:
def …我想要的是:
obj = Foo.new(0)  # => nil or false
这不起作用:
class Foo
  def initialize(val)
    return nil if val == 0
  end
end
我知道在C/C++/Java/C#中,我们无法在构造函数中返回一个值.
但我想知道Ruby是否可行.
我在c ++中有以下类定义:
struct Foo {
  int x;
  char array[24];
  short* y;
};
class Bar {
  Bar();
  int x;
  Foo foo;
};
并且想要在Bar类的初始值设定项中将"foo"结构(及其所有成员)初始化为零.可以这样做:
Bar::Bar()
  : foo(),
    x(8) {
}
......?
或者foo(x)在初始化列表中的作用是什么?
或者结构甚至从编译器自动初始化为零?
以下是初始化静态只读字段的两种不同方法.两种方法之间有区别吗?如果是的话,什么时候应该优先于另一个呢?
class A
{
    private static readonly string connectionString =
        WebConfigurationManager.ConnectionStrings["SomeConnection"].ConnectionString;
}
class B
{
    private static readonly string connectionString;
    static B()
    {
        connectionString =
            WebConfigurationManager.ConnectionStrings["SomeConnection"].ConnectionString;
    }
}
我对CoreData有一点该死的问题.我想插入一个新的Object,所以我首先要创建一个.这是由该代码完成的:
Challenges *newChallenge = [[Challenges alloc] init];
[newChallenge setName:@"TestChallenge"];
[newChallenge setRounds:[[NSNumber alloc] initWithInt:12]];
[newChallenge setShots:[[NSNumber alloc] initWithInt:5]];
[newChallenge setDate:[NSDate date]];
但是在alloc init之后我得到了这个错误:
CoreData: error: Failed to call designated initializer on NSManagedObject class 'Challenges'
黑客出了什么问题?
我正面临一个用例,我想声明一个static final带有初始化语句的字段,该语句被声明为抛出一个已检查的异常.通常,它看起来像这样:
public static final ObjectName OBJECT_NAME = new ObjectName("foo:type=bar");
我在这里遇到的问题是ObjectName构造函数可能会抛出各种已检查的异常,我并不关心这些异常(因为我知道我的名字是有效的,如果它没有崩溃就会崩溃).java编译器不会让我忽略它(因为它是一个经过检查的异常),我宁愿不诉诸:
public static final ObjectName OBJECT_NAME;
static{
    try{
        OBJECT_NAME = new ObjectName("foo:type=bar");
    }catch(final Exception ex){
        throw new RuntimeException("Failed to create ObjectName instance in static block.",ex);
    }  
}
因为静态块确实非常难以阅读.有没有人有一个关于如何以一个漂亮,干净的方式处理这种情况的建议?
所以我刚刚升级到Xcode 6.3 Beta 3,并且出现了很多与以下内容相关的错误:
Initializer不会覆盖其超类中的指定初始值设定项.
override init() {
    super.init()
}
例如,这是一个UIButton类:
class CustomButton: UIButton {
    var target: AnyObject!
    var selector: Selector!
    var action: (() -> Void)!
    override init() { // Initializer does not override a designated initializer from its superclass
        super.init() // Must call a designated initializer of the superclass 'UIButton'
    }
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
}
这是我的UIViewController课程之一:
class CustomAlertView: UIViewController {
    required init(coder aDecoder: …通常用于{0}初始化a struct或a,array但考虑第一个字段不是标量类型时的情况.如果第一个字段struct Person是另一个struct或数组,则该行将导致错误(error: missing braces around initializer).
struct Person person = {0};
至少GCC允许我使用空的初始化列表来完成同样的事情
struct Person person = {};
但这是有效的C代码吗?
另外:这条线是否保证给出相同的行为,即零初始化struct?
struct Person person;
我正在尝试在Swift中启动一个基于Cocoa项目的新文档,并希望创建一个子类NSWindowController(如Apple的基于文档的应用程序指南中所推荐的).在ObjC中,您将创建一个NSWindowController子类的实例,该子类发送initWithWindowNibName:消息,相应地实现,调用超类方法.
在斯威夫特init(windowNibName)仅作为一种方便的初始化,类的指定初始化NSWindowController就是init(window)这显然想让我在一个窗口中通过.
我不能super.init(windowNibName)从我的子类调用,因为它不是指定的初始化器,所以我显然必须实现convenience init(windowNibName),而这又需要调用self.init(window).但是,如果我只有我的nib文件,如何访问nib文件的窗口以发送到该初始化程序?
我在这里问了一个问题:涉及非功能代码的initializer_list返回的生命周期扩展:
const auto foo = [](const auto& a, const auto& b, const auto& c) { return {a, b, c}; };
我相信lambda试图回归intializer_list(这很糟糕,不要这样做.)但我得到了一个评论:
它不是一个
initializer_list,它是一个初始化列表.两件不同的事情.
我只是认为,无论何时你做了一个花括号列表,你都在创建一个intializer_list.如果那不是正在发生的事情,花括号中的列表是什么?
c++ initialization initializer curly-braces initializer-list