You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++程序无法打印类实例的成员属性该如何解决

问题原因

构造函数的形参名和类的成员变量名完全重名,赋值语句height = height;实际操作的是局部的形参变量,类本身的成员变量始终处于未初始化状态,访问未初始化的变量属于C++未定义行为,因此会出现控制台无输出、运行异常的情况。

修复方案

有两种常见的修复方式:

方案1:使用this指针明确指定成员变量

在赋值时用this->前缀标记要操作的是类的成员变量:

#include <iostream>

using namespace std;

class Monolith{
    public:
        int height;
        int weight;
        string material;
        string place;

        Monolith (int height, int weight, string material, string place){
           this->height = height;
           this->weight = weight;
           this->material = material;
           this->place = place;
        }
};

int main()
{
    Monolith EiffelTower(300, 10000, "Iron", "Paris");
    cout << EiffelTower.place;

    return 0;
}

方案2:使用成员初始化列表(更推荐)

初始化列表可以直接规避变量名冲突问题,同时执行效率更高:

#include <iostream>

using namespace std;

class Monolith{
    public:
        int height;
        int weight;
        string material;
        string place;

        Monolith (int h, int w, string m, string p)
        : height(h), weight(w), material(m), place(p)
        {}
};

int main()
{
    Monolith EiffelTower(300, 10000, "Iron", "Paris");
    cout << EiffelTower.place;

    return 0;
}

内容的提问来源于stack exchange,提问作者The Fear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 20:09:03