Tag: 构造函数

JavaScriptinheritance和构造函数属性

考虑下面的代码。 function a() {} function b() {} function c() {} b.prototype = new a(); c.prototype = new b(); console.log((new a()).constructor); //a() console.log((new b()).constructor); //a() console.log((new c()).constructor); //a() 为什么不更新为b和c的构造函数? 我做inheritance错了吗? 什么是更新构造函数的最好方法? 此外,请考虑以下事项。 console.log(new a() instanceof a); //true console.log(new b() instanceof b); //true console.log(new c() instanceof c); //true 假设(new c()).constructor等于a()和Object.getPrototypeOf(new c())是a{ } ,那么instanceof怎么可能知道new c()是c一个实例呢? http://jsfiddle.net/ezZr5/

调用超类构造函数的规则是什么?

从子类调用超类构造函数的C ++规则是什么? 例如,我知道在Java中,你必须做它作为子类构造函数的第一行(如果你不这样做,假设隐式调用一个无参的超级构造函数 – 如果缺less的话会给你一个编译错误) 。

使用.apply()和'new'操作符。 这可能吗?

在JavaScript中,我想创build一个对象实例(通过new运算符),但将任意数量的parameter passing给构造函数。 这可能吗? 我想要做的是这样的(但下面的代码不起作用): function Something(){ // init stuff } function createSomething(){ return new Something.apply(null, arguments); } var s = createSomething(a,b,c); // 's' is an instance of Something 答案 从这里的回答可以明显看出,没有内build的方法可以用new运算符调用.apply() 。 但是,人们提出了一些非常有趣的解决scheme。 我最喜欢的解决scheme是从马修Crumley (我已经修改它通过arguments属性)这一个: var createSomething = (function() { function F(args) { return Something.apply(this, args); } F.prototype = Something.prototype; return function() { return new F(arguments); […]

显式的关键字是什么意思?

有人在C ++中发布了关于explicit关键字含义的另一个问题的评论。 那么,这是什么意思?

在Derived.prototype = new Base中使用“new”关键字的原因是什么?

下面的代码是做什么的: WeatherWidget.prototype = new Widget; 其中Widget是一个构造函数,我想用一个新的函数WeatherWidget扩展Widget的“类”。 什么是new关键字在那里做,如果被遗漏会发生什么?

types名称后的圆括号与新的有什么不同?

如果“testing”是一个普通的类,是否有任何区别: Test* test = new Test; 和 Test* test = new Test();

三规则与C ++ 11成为五大规则?

所以,在看了这个关于右值引用的精彩演讲后,我认为每个类都会受益于这样一个“移动构造函数”, template<class T> MyClass(T&& other) ,当然还有一个“移动赋值运算符”, template<class T> MyClass& operator=(T&& other)正如Philipp在他的回答中指出的那样,如果它有dynamic分配的成员,或者通常存储指针。 就像你应该有一个copy-ctor,赋值运算符和析构函数,如果前面提到的点适用。 思考?

具有空括号的默认构造函数

有没有什么好的理由,一个空的圆括号(圆括号)是无效的调用C ++中的默认构造函数? MyObject object; // ok – default ctor MyObject object(blah); // ok MyObject object(); // error 我似乎每次都会自动input“()”。 有没有很好的理由,这是不允许的?

这是什么奇怪的冒号成员(“:”)在构造函数中的语法?

最近我见过一个例子如下: #include <iostream> class Foo { public: int bar; Foo(int num): bar(num) {}; }; int main(void) { std::cout << Foo(42).bar << std::endl; return 0; } 这是什么奇怪的: bar(num)是什么意思? 它似乎似乎初始化成员variables,但我从来没有见过这种语法。 它看起来像一个函数/构造函数调用,但为int ? 对我来说没有意义。 也许有人可以启发我。 顺便说一下,还有没有其他的深奥的语言function,你永远不会find一个普通的C + +书?

为什么没有调用构造函数?

这段代码并不像我期望的那样。 #include<iostream> using namespace std; class Class { Class() { cout<<"default constructor called"; } ~Class() { cout<<"destrutor called"; } }; int main() { Class object(); } 我期望输出的默认构造函数叫',但我没有看到任何东西作为输出。 问题是什么?