namespace pairDemo{
template<typename L, typename R>
class pair{
public:
pair(const L& left,const R& right)
:lft(left),rht(right)
{
}
pair(const pair<L,R>& p)
:lft(p.lft),rht(p.rht)
{
}
L left() const{
return lft;
}
R right() const{
return rht;
}
void left(const L& left){
lft = left;
}
void right(const R& right){
rht = right;
}
private:
L lft;
R rht;
};
}
// ------------------------------------------- --------關鍵字「const」如何工作?
#include "pairTemp.h"
#include <iostream>
using namespace std;
pairDemo::pair<int, double> func(int x, double y){
pairDemo::pair<int, double> temp(x*2, x+y);
return temp;
}
int main(){
int x = 2; double y = 3.55;
pairDemo::pair<int, double> myPair = func(x,y);
cout << myPair.left() << myPair.right();
}
我有一個問題,構造函數的參數,如果我不宣佈「常量」,函數func()將有一個錯誤。我不知道爲什麼,任何人都可以幫助我。
如果你沒有聲明什麼'const'?你得到的錯誤是...? – 2012-02-24 21:59:38
你不在哪裏聲明const,什麼是錯誤,以及錯誤是哪一行? – 2012-02-24 22:00:11
構造函數參數中的「const」。如果我沒有delcare,func()會有一個錯誤,它不能將int轉換爲int&。現在我知道臨時應該使用const了。 – titus 2012-02-24 22:42:47