繁体   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