2017-10-16 87 views
0

是否有可能使结构模仿其中的一个元素?例如:直接访问结构的元素

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;工作表现?

+1

让你的返回类型'双&',找到[固体C++的书(https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – scohe001

+0

HTTP ://www.learncpp.com/cpp-tutorial/98-overloading-the-subscript-operator/ – zzxyz

+0

'struct example_struct var;'是C.你不需要struct这里。 – 2017-10-16 17:56:07

回答

4

为了使var[1]=3正常工作,您需要返回参考,而不是副本。

struct example_struct 
{ 
    double x[2]; 
    double& operator[](int i) return x[i];}; 
}