我的函数get_num
返回变量long int
。错误:无法从'long'转换为'int'
我想写的下一个操作员:
long int& operator [] (long int i) {
long int a = get_num(i);
int& b = a;
return b;
}
,但我得到了一个错误:
error C2440: 'initializing' : cannot convert from 'long' to 'int &'
error C2440: 'return' : cannot convert from 'int' to 'long &'
我怎么能解决这个问题不改变的get_num
的功能?
任何帮助赞赏!
我有一个类:
class B {
B* next;
long int nom;
long int denom;
public:
long int get_nom() {return nom; }
long int get_denom() {return denom; }
};
class List {
B* head;
public:
long int& operator [] (long int desired_denom) {
// here I search the node that containts the denom that is equal to desired_denom
// and insert it to tmp (it's a pointer to B).
long int a1 = tmp->get_nom()
long int& a2 = a1;
return a2;
}
};
现在在
main
,我想做的事:
int main() {
A a; // assume that it creates the list of B and put values in each node (each B)
// here I want to do:
a[2] = 3; // it should search the node that his denom is equal to 2, and puts 3 instead of his nom
return 0;
}
例如:
如果我的名单是:
(nom=5, denom=6)->(nom=1,denom=8)->(nom=4, denom=2)->NULL
a[2]=3
搜索他的denom为2节点行(这是第三点),并设置自己的NOM为3
所以这行后,我的名单将是:
(nom=5, denom=6)->(nom=1,denom=8)->(nom=3, denom=2)->NULL
为什么你首先返回一个整数的引用?此外,返回一个本地自动变量的引用是UB。 – 2013-04-21 19:03:24
@ H2CO3返回一个引用对于运算符[]' – 2013-04-21 19:04:41
@DavidHeffernan是完全正常的,但不是对_local_变量的引用。 – 2013-04-21 19:05:37