鱼C论坛

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

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

[复制链接]
发表于 2025-2-23 23:27:56 | 显示全部楼层 |阅读模式

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

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

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;
}
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

  1. #include <iostream>
  2. #include <string>

  3. using namespace std;

  4. class Person {
  5. public:
  6.     string name;
  7.     int age;
  8.     string gender;
  9.     int score;

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

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

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

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

  21.     return 0;
  22. }
复制代码


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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-5-10 00:28

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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