[英]How can I build this typ of class interface
I am interested in trying something where I create a custom type and then access to its members using dot semantics. 我对尝试创建自定义类型然后使用点语义访问其成员的方法感兴趣。 For example: 例如:
Class A{ //simplified, omitting constructors and other methods
private:
float numbers[3];
public:
float x(){ return numbers[0]; }
float y(){ return numbers[1]; }
float z(){ return numbers[2]; }
}
So I can do something like this: 所以我可以做这样的事情:
A a;
//do stuff to populate `numbers`
float x=a.x;
But I would also like to make the elements in numbers
lvalues so I can do something like this: 但是我也想使numbers
的元素成为左值,所以我可以做这样的事情:
A a;
a.y=5; //assigns 5 to numbers[1]
How can I do this setting method? 如何设置此方法?
First. 第一。 You made functions x, y and z but assigning them to float. 您制作了函数 x,y和z,但将它们分配为float。 This wouldn't work. 这行不通。 Second. 第二。 Change these functions to return referencies: 更改这些函数以返回引用:
class A{ //simplified, omitting constructors and other methods
private:
float numbers[3];
public:
float & x(){ return numbers[0]; }
float & y(){ return numbers[1]; }
float & z(){ return numbers[2]; }
};
...
A point;
float x = point.x();
point.x() = 42.0f;
There's another way: declare referencies as a members of class and initialize them in c-tor: 还有另一种方式:将引用声明为类的成员,然后在c-tor中对其进行初始化:
class A{ //simplified, omitting constructors and other methods
private:
float numbers[3];
public:
float & x;
float & y;
float & z;
A() : x( numbers[ 0 ] ), y( numbers[ 1 ] ), z( numbers[ 2 ] ) {}
};
...
A point;
float x = point.x;
point.x = 42.0f;
PS Pay an attention on comment, that gave @MikeSeymour PS注意评论,这给了@MikeSeymour
You can return a reference to allow assignment: 您可以返回引用以允许分配:
float & x(){ return numbers[0]; }
^
// usage
A a;
a.x() = 42;
You should also have a const
overload, to allow read-only access to a const
object: 您还应该具有const
重载,以允许对const
对象的只读访问:
float x() const {return numbers[0];}
^^^^^
// usage
A const a = something();
float x = a.x();
Not unless you actually have public variables named x, y and z. 除非您实际上有名为x,y和z的公共变量。
Or you can return a reference and then do ay() = 5
或者您可以返回引用,然后执行ay() = 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.