c++中->和.的區別
阿新 • • 發佈:2018-12-27
->用在指標型別的類例項的,而.用在例項化物件的指向。
下面是例子
#include <iostream> using namespace std; class Complex { private: double real; double image; public: Complex() { this->image=0; this->real=0; } Complex(double real,double image) { this->real=real; this->image=image; } friend Complex operator+(Complex com1,Complex com2); void show(); }; Complex operator+(Complex com1,Complex com2) { return Complex(com1.real+com2.real,com1.image+com2.image); //下面是錯誤的 //return Complex(com1->real+com2->real,com1->image+com2->image); } void Complex::show() { cout<<"實數部分為"<<this->real<<endl; cout<<"虛數部分為"<<this->image<<endl; //下面是錯誤的 //cout<<"實數部分為"<<this.real<<endl; //cout<<"虛數部分為"<<this.image<<endl; } int main() { Complex com1(2,5),com2(3,9),sum; sum=com1+com2; sum.show(); system("pause"); return 1; }