如何在不调用同一类构造函数的情况下创建对象? [英] How to create an object without calling the same class constructor?

查看:161
本文介绍了如何在不调用同一类构造函数的情况下创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个不应调用构造函数的对象..

 #include   <   iostream  > 
 #include   <   conio.h  > 
 使用 命名空间 std;
课程我
{
公共:
我()
{
cout<< " ;
}
无效 fun()
{
cout<< " << endl;
}
};
无效 main()
{
我b;
b.fun();
getch();
} 


输出:

hi
fun



我的预期输出是:

fun



我必须在该程序中进行哪些更改才能带来预期的输出..

解决方案

简短的答案:您不能那样做.
更长的答案:您不能这样做,您为什么要这样做?


每个类都需要有一个构造函数.您不需要让它做任何有用的事情.编写一个空的构造函数,然后继续.


简短的答案:您不能那样做.

作弊答案:make fun()静态

  class 我
{
公共:
  我()
  {
    cout<< " ;
  }
  静态 无效 fun()
  {
    cout<< " << endl;
  }
};
无效 main()
{
  b :: fun();
  getch();
} 



危险的作弊答案:不要调用构造函数

  void  main()
{
  me * b =  0 ;
  b-> fun();
} 


在此示例中,这是可行的,因为me类没有成员数据,也没有虚拟函数(因此没有虚拟函数表作为隐式成员数据).如果我看到有人提交这样的代码,我建议他们被解雇.

在一次采访中,他们可能会对您是否了解找到此解决方案"所需的理解感兴趣,并说在这种情况下它会起作用,但我不会真正做到". /blockquote>

I want to create an object that should not call my constructor..

#include<iostream>
#include<conio.h>
using namespace std;
class me
{
public:
	me()
	{
cout<<"hi";
	}
	void fun()
	{
		cout<<"\nfun"<<endl;
	}
};
void main()
{
me b;
b.fun();
getch();
}


output:

hi
fun



My expected output is:

fun



What changes i have to make in that program to bring expected output..
The task is to create an object of that class and that should not call the constructor..

解决方案

Short answer: You cannot do that.
Longer answer: You cannot do that, is there any reason why do you want to do that?


Every class is required to have a constructor. You are not required to have it do anything useful. Write an empty constructor and move on.


Short answer: you cannot do that.

Cheating answer: make fun() static

class me
{
public:
  me()
  {
    cout<<"hi";
  }
  static void fun()
  {
    cout<<"\nfun"<<endl;
  }
};
void main()
{
  b::fun();
  getch();
}



Dangerous, cheating answer: don''t call the constructor

void main()
{
  me* b = 0;
  b->fun();
}


This works, in this example, because the me class has no member data and no virtual functions (so no virtual function table as implicit member data). If I ever saw anyone submit code like this, I''d recommend they were sacked.

In an interview, they might have been interested in seeing if you had the understanding required to find this ''solution'', and to say "In this case it would work, but I wouldn''t do it for real".


这篇关于如何在不调用同一类构造函数的情况下创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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