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

C++代码在main函数访问类成员报错,请求定位问题并解释

代码错误分析与修复方案

错误定位

第29行的myRectangle.width = 5;是导致报错的原因。

错误原因详解

在C++中,类的成员默认访问权限为私有(private)。你定义的Rectangle类里,width和height未指定访问修饰符,因此默认属于私有成员。私有成员的访问范围被限制在类内部,只有类的成员函数(比如setDimensions、calculateArea)才能直接读写这些变量,类外部的代码(如main函数)无法直接访问私有成员,这就是Visual Studio提示错误的核心原因。

修复方案

方案一:使用类提供的成员函数修改(推荐)

类中已经定义了setDimensions函数,专门用于修改矩形的宽高,直接调用该函数即可,这符合面向对象的封装原则:

#include <iostream>
using namespace std;

class Rectangle {

    int width;
    int height;

public:
    Rectangle(int w, int h) {
        width = w;
        height = h;
    }

    void setDimensions(int w, int h) {
        width = w;
        height = h;
    }

    int calculateArea() {
        return width * height;
    }
};

int main() {
    Rectangle myRectangle(3, 4);

    cout << "Initial Area: " << myRectangle.calculateArea() << endl;
    // 使用setDimensions修改宽为5,高保持4
    myRectangle.setDimensions(5, 4); 

    cout << "Updated Area: " << myRectangle.calculateArea() << endl;

    return 0;
}

方案二:修改成员访问权限(不推荐)

将width和height的访问权限改为公有(public),这样外部代码就能直接访问,但这种做法破坏了类的封装性,会导致代码的可维护性降低:

class Rectangle {
public: // 新增public修饰符
    int width;
    int height;

public:
    Rectangle(int w, int h) {
        width = w;
        height = h;
    }

    void setDimensions(int w, int h) {
        width = w;
        height = h;
    }

    int calculateArea() {
        return width * height;
    }
};

内容的提问来源于stack exchange,提问作者Siayam Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 14:05:04