c++自学 关于构造函数的基础

来源:互联网 发布:淘宝店铺联盟怎么开通 编辑:程序博客网 时间:2024/05/29 14:44


1.构造函数
    构造函数在创建对象时就被调用了;
#include<iostream>
using namespace std;
class fish
{
public:
    fish()
    {
        cout<<"fish"<<endl;
    }
};
int main()
{
    fish a;//这是对象a被创建了,与此同时函数fish()被调用;
}

//输出fish
2.重载函数
   简单地说就是重复使用一个函数名,例如上述所说的fish(),但是对于构造函数其参数必须不同;例如fish(),fish(int a)等
   #include<iostream>
using namespace std;
class fish
{
public:
    fish()
    {
        cout<<"fish "<<endl;
    }
    fish(int a)
    {
        cout<<a<<endl;
    }
};
int main()
{
    fish a;
    fish b(5);
}

//输出就为fish 和 5
3.构造函数中已有默认值
  在上述fish(int a)中a的值并没有确定,但是c++ 还可以使构造函数具有默认值,此时即使在调用函数时没有给予初值,函数任然可以被调用;
  但是对于带有默认值的构造函数由于条件限制太多,建议谨慎使用。个人认为这种函数只能在第一个参数被传递至函数体中才能将第二个参数传递过去;
  #include<iostream>
using namespace std;
class fish
{
private:
    string name;
    int age;
public:
    fish(string aname = "zyt",int aage = 6)
    {
        name = aname;
        age = aage;
        cout<<name<<"  "<<age<<endl;
    }
};
int main()  //这样是正确的
{
    fish a("zytxjx");
}
int maim()   //这样同样可行
{
 fish("zytxjx",8);
}
int main()   //这样定义是会报错的,错误大致意思为讲一个int类型的值赋予了插入型
{
    fish(6);
}

0 0
原创粉丝点击