C++,类的构造函数重载,语法练习

#include <iostream>
#include <string>
using namespace std;

class Student
{
public:
	// 存
	void setname(string s){	name = s;}
	void setage(int y){age = y;	}
	void setaddress(string add){address = add;}    
	// 取
	string getname(){return name;}
	int getage(){return age;}
	string getaddress(){return address;}

	Student & show()
	{
		cout<<"调用成员函数show-------"<<endl;
		cout<<"姓名: "<<name<<" --- 年龄: "<<age<<" ---- 住址: "<<address<<endl; 
		return *this; 
	}    

	
    //-- 引入构造函数:初始化成员,与类同名,没有返回值
	Student(string name,int age,string address)
	{
		this->name = name; this->age = age; this->address = address;
        cout<<this->name<<":调用构造函数---"<<endl;
	    cout<<"姓名: "<<this->name<<" --- 年龄: "<<this->age<<" ---- 住址: "<<this->address<<endl; 
	}

	//--- 引入 析构函数
	 ~Student(){ cout<<this->name<<":调用析构函数---"<<endl;}
	 

protected:

private:
	string name;
	int    age;
	string address;
};


//---

 

 

//  ------   重载构造函数:

 

    //-- 引入构造函数:初始化成员,与类同名,没有返回值
 Student(string name,int age,string address)
 {
  this->name = name; this->age = age; this->address = address;
        cout<<this->name<<":调用构造函数---"<<endl;
     cout<<"姓名: "<<this->name<<" --- 年龄: "<<this->age<<" ---- 住址: "<<this->address<<endl;
 }

 
 //-- 重载构造函数
 Student()
 {
  this->name = "张光明"; this->age = 30; this->address = "民主路150号";
        cout<<this->name<<":调用重载构造函数---"<<endl;
  cout<<"姓名: "<<this->name<<" --- 年龄: "<<this->age<<" ---- 住址: "<<this->address<<endl;
 }

 



 

//-----  

下面就有问题了,为何 x2 没有调用重载的构造函数?

 

// ---- 如 这样 写 Student  x2; // x2调用了 重载的构造函数

 

 
最后干脆把2个构造函数并在一起: 把重载函数的参数直接在原构造函数参数列表中作为默认值

    即使这样,Studen x2()的写法还是没有调用构造函数的,必须写成 Student  x2

 
 

   //-- 引入构造函数:初始化成员,与类同名,没有返回值
 Student(string name="张光明",int age=30,string address="民主路150号")
 {
  this->name = name; this->age = age; this->address = address;
        cout<<this->name<<":调用构造函数---"<<endl;
     cout<<"姓名: "<<this->name<<" --- 年龄: "<<this->age<<" ---- 住址: "<<this->address<<endl; 
 }


 

x2 初始化则用的构造函数中的默认值:

 

 

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值