直接访问结构的元素
问题描述:
是否有可能使结构模仿其中的一个元素?例如:直接访问结构的元素
struct example_struct
{
double x[2];
double operator[](int i){return x[i];};
}
struct example_struct var;
现在,假设var.x
莫名其妙地被初始化,像std::cout<<var[1];
明确的工作表现,但我应该怎么做才能让像var[1]=3;
工作表现?
答
为了使var[1]=3
正常工作,您需要返回参考,而不是副本。
struct example_struct
{
double x[2];
double& operator[](int i) return x[i];};
}
让你的返回类型'双&',找到[固体C++的书(https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – scohe001
HTTP ://www.learncpp.com/cpp-tutorial/98-overloading-the-subscript-operator/ – zzxyz
'struct example_struct var;'是C.你不需要struct这里。 – 2017-10-16 17:56:07