【问题标题】:When calling derived class - error: taking address of temporary [-fpermissive]调用派生类时 - 错误:获取临时地址 [-fpermissive]
【发布时间】:2013-09-20 17:35:18
【问题描述】:

我一直在研究这个错误,但找不到解决方法。我有一个带有虚函数 compute() 的基类 Convert,以及一个派生类 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;
      }
    ...

【问题讨论】:

    标签: c++ gcc compiler-errors pass-by-reference


    【解决方案1】:

    该问题与基类型或派生类型无关,您试图使指针指向临时对象,这是不允许的:

    T *p = &T(); // reproduces the same issue for any T
    

    【讨论】:

    • 像往常一样:除非它超载:)
    • @jrok: 如果你超载operator&amp; 你应该得到你得到的
    【解决方案2】:

    L_To_G(num)temporary object。您不能将指针分配给临时对象。使用new 关键字为新对象分配新内存。

    p = new L_To_G(num)

    【讨论】:

      猜你喜欢
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-09
      • 2021-11-05
      • 1970-01-01
      相关资源
      最近更新 更多