鱼C论坛

 找回密码
 立即注册
查看: 18|回复: 1

[技术交流] 构造函数-初始化列表

[复制链接]
发表于 昨天 23:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <iostream>

using namespace std;

class Person {
public:
        string name;
        int age;
        string gender;
        int score;

        //Person() {
        //        name = "";
        //        age = 0;
        //        gender = "";
        //        score = 0;
        //}
        Person() :name(""), age(0), gender(""), score(0) { }//初始化列表的写法

        Person(string n, int a, string g, int s) :name(n), age(a), gender(g), score(s) { }

        //如果出现了形参的名字和属性名字相同的情况,系统会自动的去识别参数和属性
        Person(string name, int age, string gender) :name(name), age(age), gender(gender) { }
};

int main() {

        Person xiaoming("xiaoming", 19, "male", 99);
        cout << xiaoming.name << endl;
        cout << xiaoming.age << endl;
        cout << xiaoming.gender << endl;
        cout << xiaoming.score << endl;

        Person xiaobai("xiao.bai", 19, "male");
        cout << xiaobai.name << endl;
        cout << xiaobai.age << endl;
        cout << xiaobai.gender << endl;

        return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 昨天 23:28 | 显示全部楼层
你提供的代码缺少了 #include <iostream> 和一个完整的输出语句。我们来补充并修正一下代码:
#include <iostream>
#include <string>

using namespace std;

class Person {
public:
    string name;
    int age;
    string gender;
    int score;

    // 默认构造函数
    Person() : name(""), age(0), gender(""), score(0) {}

    // 带参数的构造函数
    Person(string n, int a, string g, int s) : name(n), age(a), gender(g), score(s) {}

    // 带部分参数的构造函数
    Person(string name, int age, string gender) : name(name), age(age), gender(gender), score(0) {}
};

int main() {
    Person xiaoming("xiaoming", 19, "male", 99);
    cout << "Name: " << xiaoming.name << ", Age: " << xiaoming.age 
         << ", Gender: " << xiaoming.gender << ", Score: " << xiaoming.score << endl;

    return 0;
}

这个代码会正确输出小明的信息。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-2-24 08:19

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表