我一直在研究这个错误,但找不到解决方法。我有一个基类转换与虚函数compute()和派生类L_To_G(升加仑)。在我的main.cpp文件中,声明:
p =& L_To_G(num);
给了我以下错误:
../ main.cpp:在函数'int main()'中:
../ main.cpp:37:20:错误:获取临时[-fpermissive]的地址 p =& L_To_G(num);
头文件中的代码:
class Convert
{
protected:
double val1, val2; //data members
public:
Convert(double i) //constructor to initialize variable to convert
{
val1 = i;
val2 = 0;
}
double getconv() //accessor for converted value
{
return val2;
}
double getinit() //accessor for the initial value
{
return val1;
}
virtual void compute() = 0; //function to implement in derived classes
virtual ~Convert(){}
};
class L_To_G : public Convert //derived class
{
public:
L_To_G(double i) : Convert(i) {}
void compute() //implementation of virtual function
{
val2 = val1 / 3.7854; //conversion assignment statement
}
};
main.cpp文件中的代码:
int main()
{
...
switch (c)
{
case 1:
{
p = &L_To_G(num);
p->compute();
cout << num << " liters is " << p->getconv()
<< " gallons " ;
cout << endl;
break;
}
...
答案 0 :(得分:2)
问题与基类或派生类型无关,您试图使指针引用临时,并且不允许:
T *p = &T(); // reproduces the same issue for any T
答案 1 :(得分:1)
L_To_G(num)
是temporary object。您不能将指针指定给临时对象。使用new
关键字为新对象分配新内存。
p = new L_To_G(num)