新的运算符来创建对象数组并使用特定的构造函数重载?可能的? [英] new operator to create array of objects and use a particular constructor overload? Possible?

查看:87
本文介绍了新的运算符来创建对象数组并使用特定的构造函数重载?可能的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设A是用户定义的类(如下所示)

  class  A
{
DWORD m_a,m_b;
布尔m_bFlag;

公共:
一个()
{
ZeroMemory( sizeof (** span class ="code-keyword"> this  ));
}

A(BOOL bFlag)
{
m_bFlag = bFlag;
}
};

无效 foo()
{
* p1,* p2,* p3;


/*  我知道这可以工作*/
p1 =  A(TRUE);



/*  这样也可以*/
p2 =  A [ 10 ];


/*  将这些结合起来是可能的吗? */
p3 =  A(TRUE)[ 10 ];

/*  
我希望调用重载A :: A(BOOL)而不是默认构造函数,并且所有对象都应该发生这种情况.
有什么办法可以做到这一点?
*/
} 



我想将TRUE传递给所有实例.

我知道还有其他选择,例如创建一个单独的函数,该函数将分配成员变量并将其设置为TRUE,最后返回基指针.

yeswekey写道:

但是有可能在没有任何解决方法的情况下做到这一点吗?


不.
语言语法不允许这样做.您必须使用一种解决方法(例如,可以仅使用一个带有一个可选BOOL参数的重载构造函数):

 A(BOOL bFlag = TRUE)
{
  //  .. 
} 


Assume that A is a user defined class (as shown below)

class A
{
	DWORD m_a, m_b;
	BOOL m_bFlag;

public:
	A()
	{
		ZeroMemory(this, sizeof(*this));
	}

	A(BOOL bFlag)
	{
		m_bFlag = bFlag;
	}
};

void foo()
{
	A *p1, *p2, *p3;


	/* I know this will work */
	p1 = new A(TRUE);



	/* This should be fine too */
	p2 = new A[10];


	/* Combining these... is something like this possible? */
	p3 = new A(TRUE)[10];
	
	/*
	I want the overload A::A(BOOL) to be called instead of default constructor and this should happen with all the objects.
	Is there any way to accomplish this?
	*/
}



I want to pass TRUE to all instances.

I know there are alternatives like creating a seperate function that''ll allocate and set the member variable to TRUE and finally return the base pointer.
But is it possible to do that without any workaround?

解决方案

yeswekey wrote:

But is it possible to do that without any workaround?


Nope.
The language syntax doesn''t allow that. You must use a workaround (you may, for instance use only one overloaded constructor with one optional BOOL argument):

A(BOOL bFlag = TRUE)
{
  //..
}


这篇关于新的运算符来创建对象数组并使用特定的构造函数重载?可能的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆