对C++对象实例化的测试

#include <iostream>
using namespace std;
class class1 {
	
	public:
	class1(){

	}
	class1(int i ){
	
	}
	void  show(){

		cout<<"this is output by class1 ! \n ";
	}
};
int main(){
	// static allocation :
	/*

	class1 oneclass();

	oneclass.show();
	
	error : request show() function of non-class oneclass .

	because : compile thinks of oneclass1 oneclass() as of function declaration with 

	name 'oneclass' and the return type class1 

	*/
/*
	class1 secondclass(1);

	secondclass.show();
*/
	//dynamic allocation :
	
	class1 * thirdclass = new class1();

	thirdclass->show();

	return 0;
}

 

 总结一下:

1. 当使用类的无参构造函数来实例化对象时,有两种方法:

   类名  * x = new 类名();

  类名  x;

2 . 当使用有参的构造函数时,有两种方法:

  类名 * x = new 类名(参数列表); 

  类名 x(参数列表);

注 :编译器版本 : 

原文地址:https://www.cnblogs.com/caiyao/p/3660293.html