C ++获取临时地址-在将引用分配给指针时出错 [英] C++ Taking address of temporary - error while assigning reference to pointer
问题描述
该程序是用C ++编写的.我正在尝试使用void函数来扩展Line结构,该结构由整数长度和指向下一条连接的线的指针组成.有一个void Expand函数可以为结构中的行指针分配行引用.新行将是当前行大小的两倍.使用我正在使用的代码,我得到一个g ++错误获取临时[-fpermissive]的地址".谁能建议该函数将行引用的有效实例添加到行指针nextLine的方法吗?
This program is written in C++. I am trying to use a void function to expand a Line structure which consists of an integer length and a pointer to the next connected line. There is a void Expand function made to assign a line reference to the line pointer in the struct. The new line is to be double the size of the current line. With the code I am using, I get a g++ error of 'Taking address of temporary [-fpermissive]'. Could anyone suggest a way in which the function adds a valid instance of a line reference to the Line pointer nextLine?
struct Line
{
int length;
Line* nextLine;
};
Line NewLine(Line& lineRef)
{
Line newLine;
newLine.length = lineRef.length * 2;
return newLine;
}
void Expand(Line& lineRef)
{
//Error here states: Taking address of temporary [-fpermissive]
lineRef.nextLine = &NewLine(lineRef);
}
int main() {
Line line;
Expand(line);
cout << line.length << endl;
cout << line.nextLine->length << endl;
return 0;
}
推荐答案
此方法有效
struct Line
{
int length;
Line* nextLine;
~Line(){delete nextLine;}
//Make copy constructor and assignment operator private
};
void Expand(Line* lineRef)
{
lineRef->nextLine = new Line;
lineRef->nextLine->length = 2*(lineRef->length) ;
}
int main()
{
Line* line = new Line;
line->length = 5;
Expand(line);
cout << line->length << endl;
cout << line->nextLine->length << endl;
delete line;
return 0;
}
这篇关于C ++获取临时地址-在将引用分配给指针时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!