/*声明和实现构造函数*/
/*
class Human
{
public:
Human();//声明一个构造函数
}
1.构造函数既可以在类声明内实现,也可以在类声明外实现
(1)在类声明内实现如下:
class Human
{
public:
Human()
{
}
};
(2)在类声明外实现如下:
class Human
{
public:
Human();
};
Human::Human()
{
}
*/
/*构造函数主要用于初始化*/
#include <iostream>
using namespace std;
class Human
{
private:
string name;
int age;
public:
Human()
{
age = 1;
cout<<"Constructed an instance of class Human"<<endl;
}
void SetName(string humanName)
{
name = humanName;
}
void SetAge(int humansAge)
{
age = humanAge;
}
void IntroduceSelf()
{
cout<<"I am "+name << " and "+age<<endl;
}
}
int main()
{
Human firstWoman;
firstWoman.SetName("Eve");
forstWoman.SetAge(28);
firstWoman.IntroduceSelf();
return 0;
}
/*包含多个构造函数的Human类*/
**注意**
构造函数必须和类名相同
#include<iostream>
using namespace std;
class Human
{
private:
string name;
int age;
public:
Human()
{
age = 0;
cout<<"Overloaded constructor creates ";
cout<<"Default constructor: name and age not set "<<endl;
}
Human(string humansName,int humansAge)
{
name = humansName;
age = humansAge;
cout<< "Overloaded constructor creates";
cout<<name<< " of "<< age <<" years"<<endl;
}
};
int main()
{
Human firstMan;
Human firstWoman(" Eve",20);
return 0;
}
C++构造函数的用法
最新推荐文章于 2025-04-10 19:24:17 发布