用方法代替成员赋值
Replace member assignement with methods
在c++中编写了一些代码之后,可能需要将对结构体或类的成员的访问更改为产生一些副作用的内容。在这种意义上,需要将成员的赋值重载为不同的对象。
Struct A{
int v;
}
int main(){
A a;
a.v=17;
}
有可能做这件事吗?如果不存在这种可能性,那么如何编写代码以允许灵活地将成员更改为其他成员呢?
对成员的每次访问都分为getter和setter似乎很麻烦,而且对于任何合理的使用都是不切实际的。
是的,使用代理:
struct A
{
v_proxy v;
private:
struct v_proxy
{
v_proxy( int vv = 0 ) : v{ vv }
{}
//Write access
v_proxy& operator=( int i )
{
//Put your new code here
return v = i;
}
//Read access
operator int() const
{
return v;
}
int v;
};
};
int main()
{
A a;
a.v = 0;
};
像这样编写一个通用的代理来允许在通用的非get/set语法中自定义读/写是很容易的。
EDIT:有人声称这不能正确地模仿c#属性的行为,因为在c#中我们可以从属性中访问this
。只需要添加一个对象的引用并将其传递给代理函数。不要忘记将代理类设置为类的朋友,为this
引用提供完全访问权限:
class A
{
A() : v{ *this }
{}
friend struct v_proxy
{
v_proxy( A& ref , int vv = 0 ) : v{ vv } , This{ std::ref( ref )
{}
//Write access
int& operator=( int i )
{
//Put your new code here, for example:
This.foo();
return v = i;
}
//Read access
operator int() const
{
return v;
}
int v;
private:
std::reference_wrapper<A> This;
};
相关文章:
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 复制赋值函数如何访问另一个对象的私有成员(Stroustroup 原则和实践书)?
- 清除具有已删除赋值运算符的成员的类实例
- 如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
- 静态成员函数赋值而不带返回语句
- 我们可以直接为任何数据成员赋值. 为什么要使用构造函数?
- 通过迭代器为映射的成员赋值
- 为什么不能为基类的成员赋值?
- 如何使用其他函数返回的值为结构体成员赋值
- C++:为类中对象的数据成员赋值
- 如何为所有结构成员赋值
- 使用双指针为结构的成员赋值
- C++:成员赋值如何工作
- 用方法代替成员赋值
- 在c++中快速将基对象的所有成员赋值给派生对象
- 返回值函数中结构成员赋值的额外拷贝
- 将pair的成员赋值给变量
- c++在使用类方法给成员赋值时每次都会崩溃
- 成员赋值笛卡尔类 c++
- c++扑克游戏中的数据成员赋值