简体   繁体   English

在类构造函数中调用包含类的构造函数

[英]Calling a constructor of included class within class constructor

In class argList constructor is the instruction 在类argList构造函数是指令

args_[0] = fileName(argv[0]);

When searching for method fileName(...) it turns out that it should be a constructor of class fileName : 当搜索方法fileName(...) ,结果表明它应该是fileName类的构造函数:

inline Foam::fileName::fileName(const char* str) //Construct as copy of character array.
: string(str)    //Construct as copy of character array.
{
    stripInvalid();    //Strip invalid characters from the given string.
}

Two Questions: 两个问题:

  1. Is it really the constructor of class fileName that is called? 确实是调用的类fileName的构造函数吗?
  2. Hasn' t the constructor of fileName to be static if it was called like this? 如果像这样被调用, fileName的构造函数不是静态的吗?

greetings streight 问候声

  1. Yes - this is a really constructor of fileName class - there's no return value and the name of the method is the same as the name of the class. 是的-这是fileName类的真正构造函数-没有返回值,并且方法的名称与类的名称相同。

  2. This is not a call to the constructor, but the definition of the constructor (I guess :: is what is confusing you): 这不是对构造函数的调用,而是对构造函数的定义(我想::会让您感到困惑):

     inline Foam::fileName::fileName(const char* str) //Construct as copy of character array. 

    This is the call to the constructor: 这是对构造函数的调用:

     args_[0] = fileName(argv[0]); 

    There's no static constructor in C++. C ++中没有静态构造函数。

'1. '1。 Is it really the constructor of class fileName that is called? 确实是调用的类fileName的构造函数吗?

Yes. 是。 The constructor is called because it args_[0] is assigned a new instance of the fileName class. 之所以调用构造函数,是因为为args_ [0]分配了fileName类的新实例。

'2. '2。 Hasn' t the constructor of fileName to be static if it was called like this? 如果像这样被调用,fileName的构造函数不是静态的吗?

No. A constructor cannot be static. 否。构造函数不能为静态。 This is one of the correct ways to construct objects. 这是构造对象的正确方法之一。

Is it really the constructor of class fileName that is called? 确实是调用的类fileName的构造函数吗?

Indirectly, yes. 间接地,是的。 For a class T , the expression T(args) creates a temporary object, and initialises it by calling a suitable constructor for the arguments. 对于类T ,表达式T(args)创建一个临时对象,并通过为参数调用合适的构造函数对其进行初始化。

In this case, this constructor matches the argument type, so that's what is used. 在这种情况下,此构造函数与参数类型匹配,因此使用了该构造函数。

Hasn't the constructor of fileName to be static if it was called like this? 如果像这样调用fileName ,构造器不是静态的吗?

No, constructors can't be declared static. 不,构造函数不能声明为静态。 They can always be used to initialise either named variables, or temporaries like this one, with no special declarations. 它们始终可以用于初始化命名变量或类似此类的临时变量,而无需特殊声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM