我追求两件事.我首先想要将vector类定义为更有意义的类,例如List.我尝试了以下但它给了我一个编译错误:
template <typename T>
typedef vector<T> List<T>
Run Code Online (Sandbox Code Playgroud)
其次我想覆盖类的<<操作符vector,但我不知道如何在不创建新类的情况下继续操作.
这似乎适得其反,但我的最终目标是让非程序员(或之前没有完成过c ++的人)可以读取具有语义意义的东西.
如果你这样做,非程序员仍然无法阅读,更不用说更改代码了.但是,C++程序员在阅读代码时也会遇到很多麻烦.
如果他们无法编码,并且需要C++程序员为他们编写代码,那么他们将需要一个C++程序员来理解,维护和扩展第一个C++程序员编写的代码.
如果,OTOH,他们需要用C++编码,那么 - 惊喜! - 他们必须学会编写和阅读C++代码.
两者之间确实没有任何关系.
小智 5
typedefC++ 中没有 template ,但您可以using在 C++11 中使用 template 。
template<class T>
using List = std::vector<T>;
// ...
List<int> foo; // aka std::vector<int> foo;
Run Code Online (Sandbox Code Playgroud)
操作符重载可以在不修改类的情况下完成。
template<class T>
std::vector<T>& operator<<(std::vector<T>& vec, const T& value) {
vec.push_back(value); // or whatever you want to do.
return vec;
}
Run Code Online (Sandbox Code Playgroud)
只要把它放在某个地方,它就应该可以工作,即使是在std::vector.