当前位置: 代码迷 >> 综合 >> C++,类的构造函数重载,语法练习
  详细解决方案

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

热度:51   发布时间:2024-01-19 15:37:12.0
#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 初始化则用的构造函数中的默认值:

 

 

 

 

  相关解决方案