了解模板中的 & 运算符
Understanding the & operator in templates
所以我目前正在阅读sams 另一个例子:template <typename objectType>
objectType & GetMax (const objectType & value1, const objectType & value2)
{
if (value1 > value2)
return value1;
else
return value2;
};
Template <typename T>
class myTemplateClass
{
public:
void SetVariable (T& newValue) {m_Value = newValue; };
T& GetValue() {return m_Value;};
private:
T m_Value;
};
请帮助我理解为什么&,我知道得到数据类型的地址,在这里!这绝对不会让学习STL变得更容易..........谢谢!div =)
这不是操作符,也与模板没有(直接)关系。
它是一个类型修饰符,创建(或指示、表示或形成)一个引用,就像*
创建一个指针一样。
很多时候,这是一种优化,而不是必要的。两个三种必要的情况:
在复制构造函数中,需要避免无限递归:
class X { //X(X); // pass by value, the formal parameter is a copy of the actual parameter // the copy constructor must be called to make the copy X(const X&); // pass by reference, ok, no copy constructor call necessary };
Const引用通常避免了复制大对象,这是一个有用的优化,没有意外的行为。
当函数的返回类型,特别是
operator[]
重载,必须出现在表达式的左侧时:class Container { //Element operator[](int index); // problematic because c[i] is a temporary // so c[i] = 5; doesn't actually modify the collection, like it would with an array Element& operator[](int index); // correct
};
与此类似,对于改变左操作数的操作符,如复合赋值和流插入,必须使用非const引用形参。
任何其他情况(例如输出参数)都可以(而且我认为应该)用指针处理,因为一个函数调用看起来像按值传递,但改变了它的参数,违反了最小意外原则。完美的例子:auto_ptr<int> a = new int(5); f(a); /* is a still valid !?! */
这就引出了第三种情况(因为有人在操作符之外使用了非const引用而产生的):
在模板中,当实际类型可能是
auto_ptr
或unique_ptr
时,需要引用来避免推断破坏原始类型的类型:auto_ptr<int> a = new int(5); //template<typename T> //void dump_target( T handle ) { cout << *item; } // bad: dump_target(a); destroys *a template<typename T> void dump_target( const T& handle ) { cout << *item; } // correct
- C++:需要帮助了解运算符重载错误
- 了解运算符重载和迭代器,为什么它会打印出"wrhrwwr"?
- 了解布尔运算符==(参数 1,参数 2)
- 你能帮我了解重载一元运算符和二进制运算符之间的区别吗?
- 了解转换运算符的选择C++
- 了解运算符重载的效用
- 了解共享库中新增的重载运算符的行为
- 请帮助我了解C++中的删除运算符
- 从表中了解运算符优先级
- 了解 & Bitwise 运算符的使用
- 了解复制构造函数和复制赋值运算符
- 在 C 语言中使用 *&*&p 了解复杂的指针和地址运算符
- std::了解它是如何工作的?运算符==
- 了解C++中的运算符重载
- 了解具有最小stl优先级_queue的运算符()重载
- 了解运算符()重载
- 了解重载运算符。收到"non-standard syntax; use '&' to create a pointer to a member"错误
- 了解多个 .和 ->运算符使用?
- 了解C++运算符的范围
- 使用咬运算符了解枚举成员的初始化