创建具有属性的对象

create object with proporties

本文关键字:对象 属性 创建      更新时间:2023-10-16

如何在C++中使用 proporties 创建对象?

如果对象是矩形,我想像这样访问高度和宽度

int height = obj.height;
int width = obj.width;

该对象由函数返回。那么函数的返回类型是什么?

创建一个类Rectangle

class Rectangle {
private:
    int height;
    int width;
public:
    Rectangle(int h, int w) : height(h), width(w) {} // constructor to initialize width and height
    void getHeight() { return height; } // public getters but private attributes to stick to the encapusaltion 
    void getWidth() { return width; } 
};

有一个返回矩形的函数:

Rectangle doSomething() { // the return type is an instance of the class Rectangle
    Rectangle r(2, 3); // create a rectangle with a height of 2 and a width of 3 
    return r; // return the created object
}
int main()
{
    Rectangle r = doSomething(); // call your function
    cout << r.getHeight() << "  " << r.getWidth() << endl; // prompt width and height
}

如果要通过r.width访问widthheightr.height将访问说明符private更改为public。那么你将不再需要吸气剂了。