簡體   English   中英

OO C ++-虛擬方法

[英]OO C++ - Virtual Methods

這里只是一個非常簡單的問題。 我正在使用虛函數從文本文件中讀取。 現在,它是虛擬的,因為一方面我希望對值進行規范化,另一方面,我不希望對其進行規范化。 我試圖做到這一點:

bool readwav(string theFile, 'native');

因此,從理論上講,如果使用“本機”,則應調用此方法,但是,如果調用“ double”,則將調用該方法的其他版本。 同樣,如果該值為空,則應僅執行本機選項。

第一個問題,上面的聲明為什么不起作用? 另外,這是走下去的最佳途徑嗎? 或者,最好只使用一個類方法在選項之間進行切換。

謝謝 :)

更新:

我要去哪里錯了?

bool Wav::readwav(string theFile, ReadType type = NATIVE)
{
// Attempt to open the .wav file
ifstream file (theFile.c_str());

if(!this->readHeader(file))
{
    cerr << "Cannot read header file";
    return 0;
}

for(unsigned i=0; (i < this->dataSize); i++)
{
    float c = (unsigned)(unsigned char)data[i];

    this->rawData.push_back(c);
}

return true;
}

bool Wav::readwav(string theFile, ReadType type = DOUBLE)
{
  // Attempt to open the .wav file
  ifstream file (theFile.c_str());

  cout << "This is the double information";
  return true;
 }

因為'native'是一個多字符字符,而不是字符串。 我會使用該功能的多個版本:

bool readwavNative(string theFile);
bool readwavDouble(string theFile);

或至少一個enum作為第二個參數:

enum ReadType
{
   ReadNative,
   ReadDouble
};

//...
bool readwav(string theFile, ReadType type);

聽起來您想要的是帶有默認參數的枚舉。

enum FileType
{
  NATIVE=0,
  DOUBLE      
};

bool readwav(string theFile, FileType type = NATIVE);

默認參數存在於函數聲明中 ,請勿將其放入定義中

bool readwav(string theFile, FileType type)
{
  switch(type)
  {
    case NATIVE: { ... } break;
    case DOUBLE: { ... } break;
    default: { ... } break;
  }
}

這樣, readwav情況下,不帶參數調用readwav將使用NATIVE類型。

readwav("myfile.wav"); // Uses NATIVE type
readwav("myfile.wav", NATIVE); // Also uses NATIVE
readwav("myfile.wav", DOUBLE); // Uses DOUBLE type

這個問題已經存在,所以我認為需要一個oop答案。 我認為策略模式適合您的目的。

class WavReader
{
public:
    WavReader(const std::string fileName)
    {
        //open file and prepare to read
    }

    virtual ~WavReader()
    {
        //close file
    }

    virtual bool read()=0;
};

class NativeWavReader: public WavReader
{
public:
    NativeWavReader(const std::string fileName): WavReader(fileName){}

    virtual bool read()
    {
        //native reading method
        std::cout<<"reading\n";
        return true;
    }
};

NativeWavReader實現read從戰略方法WavReader ,如果你想其他方法創建一個類OtherWavReader不同的讀取文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM