用比例创建对象

时间:2016-02-29 08:46:31

标签: c++

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

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

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

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

1 个答案:

答案 0 :(得分:1)

创建课程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
}

如果您想通过widthheight访问r.widthr.height,请将访问说明符private更改为public。那你就不再需要吸气剂了。