-5
如何使用proporties在C++中創建對象?創建具有proporties的對象
如果對象是一個矩形,我要訪問的高度和寬度這樣
int height = obj.height;
int width = obj.width;
目的是通過一個函數返回。那麼什麼是函數的返回類型?
如何使用proporties在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
訪問width
和height
和r.height
訪問符private
改爲public
。那麼你將不再需要吸氣者了。
'struct rectangle {int height; int width; };' – songyuanyao
「proporties」是什麼意思?類似於C#中的道具**? – MikeCAT
函數的返回類型是您的矩形類型。 – molbdnilo