【发布时间】:2012-10-10 17:56:14
【问题描述】:
如果我重载 + 运算符,我可以使用 this(假设类是 className)
className operator+(className & c) { // version 1
className T;
...
return T;
}
我也可以用
className operator+(className & c) { // version 2
....
return *this;
}
这是我的问题:
在版本 2 中,我返回引用还是就这样?为什么?
版本 1 和版本 2,哪个更好?
我们经常写重载=,
另一个问题是,我在有效的 c++ 中看到:“尽可能使用 const”和“首选使用传递引用”,这是否意味着我编写类函数声明时尽可能使用 const 和引用?
如果我这样写:
template<typename T>
void Print(const T data[], const int & arraySize) // i use the const, and &
{
for(inti = 0; i < arraySize; ++i)
cout << data[i] << " ";
cout << endl;
}
当我写 main() 函数时,我写:
int iArray[14] = {7,3,32,2,55,34,6,13,29,22,11,9,1,5};
int numInts = 14; // do I need to specify numInts is const??
打印(iArray,numInts);
【问题讨论】:
标签: c++