作者 主題: 建構函式預設引數  (閱讀 4287 次)

0 會員 與 1 訪客 正在閱讀本文。

zelda

  • 憂鬱的高中生
  • ***
  • 文章數: 92
    • 檢視個人資料
建構函式預設引數
« 於: 2014-08-19 15:12 »
#include <iostream>
#include <string>

using namespace std;
class TT{
        public:
        int s;
        TT(int s = 2){
                this->s = s;
        }
        void p(){
                cout << this->s << endl;
        }
};

int main(){
        TT *a = new TT();
        a->p();
        delete a;
        return 0;
}

以上程式可以執行,沒有問題
我想提問的是
我要把類別宣告和定義分開
但不知道正確寫法
怎麼寫都是編譯錯誤

希望高手幫忙解答
感恩


Yamaka

  • 俺是博士!
  • *****
  • 文章數: 4913
    • 檢視個人資料
    • http://www.ecmagic.com
Re: 建構函式預設引數
« 回覆 #1 於: 2014-08-19 15:34 »
#include <iostream>
#include <string>

using namespace std;
class TT{
        public:
        int s;
        TT(int s = 2){
                this->s = s;
        }
        void p(){
                cout << this->s << endl;
        }
};

int main(){
        TT *a = new TT();
        a->p();
        delete a;
        return 0;
}

以上程式可以執行,沒有問題
我想提問的是
我要把類別宣告和定義分開
但不知道正確寫法
怎麼寫都是編譯錯誤

希望高手幫忙解答
感恩

你分開是怎麼寫的?
錯誤訊息是什麼?
include 檔有沒有放進主檔裡?
namespace 位置對不對?

zelda

  • 憂鬱的高中生
  • ***
  • 文章數: 92
    • 檢視個人資料
Re: 建構函式預設引數
« 回覆 #2 於: 2014-08-20 09:40 »
最後我是用這樣的寫法
a.cpp
#include "t.h"
int main(){
        TT *a = new TT(4);
        a->p();
        delete a;
        return 0;
}

t.h
#ifndef TEST
#define TEST

class TT{
        public:
        TT(int s = 2);
        void p ();
        int s;
};
#endif

t.cpp
#include "t.h"
#include <iostream>

using namespace std;

TT::TT(int s){
this->s = s;
}

void TT::p(){
        cout << this->s << endl;
}

這樣子沒有引數的時候會輸出預設的2
不知道這樣的寫法有無問題

盼高手指正