下面是℃的运动++入门第五版:编译两个相似的类时,为什么编译器输出不同?
练习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