为什么在C ++中显式调用构造函数 [英] Why explicitly call a constructor in C++
本文介绍了为什么在C ++中显式调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我们可以使用范围解析操作符,即 className :: className()
显式调用C ++中的类的构造函数。
I know we can explicitly call the constructor of a class in C++ using scope resolution operator, i.e. className::className()
. I was wondering where exactly would I need to make such a call.
推荐答案
最常见的是,在一个子类构造函数中需要一些参数:
Most often, in a child class constructor that require some parameters :
class BaseClass
{
public:
BaseClass( const std::string& name ) : m_name( name ) { }
const std::string& getName() const { return m_name; }
private:
const std::string m_name;
//...
};
class DerivedClass : public BaseClass
{
public:
DerivedClass( const std::string& name ) : BaseClass( name ) { }
// ...
};
class TestClass :
{
public:
TestClass( int testValue ); //...
};
class UniqueTestClass
: public BaseClass
, public TestClass
{
public:
UniqueTestClass()
: BaseClass( "UniqueTest" )
, TestClass( 42 )
{ }
// ...
};
...例如。
除此之外,我没有看到效用。我只是在其他代码中调用构造函数,当我太年轻,不知道我在做什么...
Other than that, I don't see the utility. I only did call the constructor in other code when I was too young to know what I was really doing...
这篇关于为什么在C ++中显式调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文