栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

构造函数中

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

构造函数中

一、带有参数的构造函数、

         --- 构造函数可以根据需要定义参数          --- 一个类中可以存在多个重载的构造函数          --- 构造函数的重载遵循C++重载的规则
class Test
{

public:
     Test(int v)
     {
      //use v to initialize member
     }
};
二、对象的定义和对象的声明不同            .对象定义 --申请对象的空间并调用构造函数            .对象声明 --告诉编译器存在这样一个对象
Test t;  //定义对象并调用构造函数

int main()
{

 //告诉编译器存在名为t的test对象  
  
   extern  Test t;
   return 0;
}

三、构造函数的自动调用

class Test
{
public:
       Test(){};
       Test(int v){};
}

int main()
{
    Test t;          //调用Test();
    Test t1(1);      //调用Test(int v)
    Test t2 = 1;     //调用Test(int v)
    return 0;
}
#include

class Test
{
public:
      Test()
	  {
		  printf("Test()n");
	  }
	  Test(int v)
	  {
		 printf("Test(int v)n"); 
		  
	  }

};

int main()
{
	Test t;
	Test t1(1);
	Test t2=1; //初始化
	
	t= t2; //赋值操作
	int i(100);  //初始化
	printf("i = %dn",i);
	
	return 0;	
}

四、构造函数的手工调用       ---一般情况下,构造函数在对象定义时被自动调用       ---一般特殊情况下,最要手工调用构造函数
#include
class Test
{
	
	
private:
    int  m_value;		
public:
      Test()
	  {
		  printf("Test()n");
		  m_value =0 ;
	  }
	  Test(int v)
	  {
		 printf("Test(int v)n"); 
		 m_value = v;
		  
	  }
	  
	  int  getValue()
	  {
		  
		  return m_value;
	  }

};

int main()
{
	Test ta[3]={Test(),Test(1),Test(2) }; //手工调用构造函数
    
	for(int i=0 ;i<3;i++)
	{
		printf("ta[%d].getValue = %dn",i,ta[i].getValue());
		
	}

	
	return 0;	
}

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/528858.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号