创建具有属性的对象
create object with 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
。那么你将不再需要吸气剂了。
相关文章:
- 类对象属性是否可以调用返回属性应具有的值的方法C++?
- 对象属性同级访问
- 迭代 Napi::对象属性(键)在 Node.js C++ N-API 中
- 是否可以在C++(17)中捕获某些对象属性的破坏性赋值事件
- 分配以下对象属性在哪里
- sutex作为对象属性和对象的向量
- C++ - 在类中包含不是类对象属性的变量是否是一种不好的做法
- 根据对象属性从列表中删除对象
- 将对象属性替换为列表
- 查找对象属性是否位于对象向量C++中
- 未知EABI对象属性44
- 按矢量中的对象属性合并排序
- 如何访问带有静态回调的对象属性
- c++中对象属性的内存分配
- 为什么对象属性的值在 c++ 中将其指针添加到映射后返回零
- 如何检查对象属性更新是否存在 std::map 键,否则插入一个新键?
- 从ASP.NET应用程序查询Active Directory对象属性将返回旧结果
- 性能对象属性与范围变量
- 无法访问对象属性
- 如何从对象方法中访问对象属性