下面是℃的運動++入門第五版:編譯兩個相似的類時,爲什麼編譯器輸出不同?
練習14.26:定義下標運算符爲您StrVec,字符串, StrBlob和StrBlobPtr類(P.566)
類StrVec
編譯沒有任何錯誤,也不warning.Below是類體:
/**
* @brief The StrVec class a std::vector like class without template
* std:string is the only type it holds.
*/
class StrVec
{
public:
//! default constructor
StrVec():
element(nullptr), first_free(nullptr), cap(nullptr){}
// etc
//! public members
std::string& operator [](std::size_t n) {return element[n];}
const std::string& operator [](std::size_t n) const {return element[n];}
// ^^^^^
// etc
private:
//! data members
std::string* element; // pointer to the first element
std::string* first_free; // pointer to the first free element
std::string* cap; // pointer to one past the end
std::allocator<std::string> alloc;
// etc
};
當編譯類String
,產生一個警告,如下所示:
/**
* @brief std::string like class without template
*
* design:
*
* [0][1][2][3][unconstructed chars][unallocated memory]
* ^ ^ ^
* elements first_free cap
*/
class String
{
public:
//! default constructor
String();
// etc
char operator [](std::size_t n) {return elements[n];}
const char operator [](std::size_t n) const {return elements[n];}
// ^^^^^
private:
//! data members
char* elements;
char* first_free;
char* cap;
std::allocator<char> alloc;
// etc
};
從編譯器警告:
warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
const char operator [](std::size_t n) const {return elements[n];}
^
編譯器我用:
gcc version 4.8.1 (Ubuntu 4.8.1-2ubuntu1~13.04)
這是爲什麼?這兩個班級之間有什麼顯着差異?
在第二個類中,您引用直接數據類型('char')而不是數據引用('std :: string&'),即指針。 – abiessu