下面的解决方案只能解码UTF-16编码的字符串,而且当ArrayBuffer的长度过大时,会报“ Maximum call stack size exceeded”的错误。
1 2 3 4 5 6 7 8 9 10 11 12
function ab2str(buf) { return String.fromCharCode.apply(null, new Uint16Array(buf)); }
function str2ab(str) { var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char var bufView = new Uint16Array(buf); for (var i=0, strLen=str.length; i < strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; }
gb2312解码
下面的解决方案能解码指定编码的字符串,包括utf-8,utf-16, iso-8859-2, koi8, cp1261, and gbk等。
1 2 3 4 5
function ab2str(arrayBuf, encodeType) { var decoder = new TextDecoder(encodeType) var u8arr = new Uint8Array(arrayBuf) return decoder.decode(u8arr) }
using namespace std; class Animal { public: virtual void eat() const { cout << "I eat like a generic Animal." << endl; } virtual ~Animal() {} }; class Wolf : public Animal { public: void eat() const { cout << "I eat like a wolf!" << endl; } }; class Fish : public Animal { public: void eat() const { cout << "I eat like a fish!" << endl; } }; class GoldFish : public Fish { public: void eat() const { cout << "I eat like a goldfish!" << endl; } }; class OtherAnimal : public Animal { }; int main() { std::vector<Animal*> animals; animals.push_back( new Animal() ); animals.push_back( new Wolf() ); animals.push_back( new Fish() ); animals.push_back( new GoldFish() ); animals.push_back( new OtherAnimal() ); for( std::vector<Animal*>::const_iterator it = animals.begin(); it != animals.end(); ++it) { (*it)->eat(); delete *it; } return 0; }
以下是虚函数 Animal::eat() 的输出:
1 2 3 4 5
I eat like a generic Animal. I eat like a wolf! I eat like a fish! I eat like a goldfish! I eat like a generic Animal.
纯虚函数示例
在C++语言中, 纯虚函数用一种特别的语法[=0]定义。
1 2 3 4
class Abstract { public: virtual void pure_virtual() = 0; };