伊莉討論區

標題: operator 我知道與法錯誤~ 但是不知道錯在哪...? [打印本頁]

作者: asas38862002    時間: 2013-11-13 08:53 PM     標題: operator 我知道與法錯誤~ 但是不知道錯在哪...?

本帖最後由 asas38862002 於 2013-11-13 08:54 PM 編輯

#include<iostream.h>
#include<stdio.h>

class apple{
      private:
              int a;
              int b;
      public :
             void input(int x,int y){a=x;y=b;}
             void dis (){cout<<"a="<<a<<" b="<<b<<endl ;}
             apple &operator+(const apple *c);
      
      
      };
      apple &apple :: operator+(const apple *c)
      {
          apple *d;
          d = new apple();
          d->a = a+ c->a;
          d->b = b + c->b;
           
            
          return *d ;  
      }
int main()
{
    apple *a,*b,*c;
    a = new apple();
    b = new apple();
    c = new apple();
    a->input(1,2);
    b->input(3,4);
    c = a + b ;
   
   
system("pause");
return 0 ;  
}
compiler 是 dev c++ 4.9.9.2
作者: dh3014    時間: 2013-11-13 09:01 PM

提示: 作者被禁止或刪除 內容自動屏蔽
作者: asas38862002    時間: 2013-11-13 09:13 PM

dh3014 發表於 2013-11-13 09:01 PM
注意你的a跟b都是private member variable
所以試圖存取d->a, d->b, c->a, c->b都會導致編譯錯誤。 ...

痾~ 好像不是這個問題欸....
就算我把那些變數放在 public 好像也是錯誤
作者: snowflying    時間: 2013-11-13 11:05 PM

1. dev c++ 4.9.9.2 不是 compiler
2. #include<iostream>
    #include<cstdio>
3. std::cout  或 using namespace std;
4. *c = *a + b ;  (根據 apple &operator+(const apple *c);)
    不過不建議用這種方式

作者: johnwanz    時間: 2013-11-14 09:35 AM

本帖最後由 johnwanz 於 2013-11-14 09:38 AM 編輯

整體來說, 可在查書, 加強
- Class的, private/public定義, 宣告 及 使用 及 new的意義及回傳..
- 變數與指標的 宣告, 使用
- operator overwrite 的定義

1.
void input(int x,int y){a=x;y=b;}=>
void input(int x,int y){a=x;b=y;}

2. &, * 的使用方式
apple &operator+(const apple *c);
=>
apple operator+(const apple& c);

3. 有input, 就不用自己再寫等於吧. (public/private的使用要注意)
d->a = a+ c->a;
d->b = b + c->b;
=>
d->input(this->a + c.a, this->b + c.b);

4. main中變數宣告方式. class直接就宣告變數, 應該沒必要用new.
apple a, b, c;

a.input(1,2);
b.input(3,4);
c = a + b ;

c.dis();
5. 一般new過, 最好有delete, 不過此處是整個程式結束.
可查閱變數生命週期的定義.







歡迎光臨 伊莉討論區 (http://a401.file-static.com/) Powered by Discuz!