2017-10-16 84 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];}; 
}