4

我的程序收到了一些关于未使用变量的编译器警告,我想知道什么是解决此问题的合适方法。

我有一个由基类继承的函数,并且在父函数的实现中,我没有使用子类所需的所有参数;当然这会导致警告,由于我不是经验丰富的程序员,我不确定修复这些警告的最佳方法是什么。

所以一个最小的例子是:

在标题中:

    class car{
     public:
       virtual void init(int color, int size)
     private:
       int size;
    }
    class sportscar : public car{
     public:
       virtual void init(int color, int size)
     private:
       int color;
       int size;
    }

在源文件中:

    void car::init(int color, int size){
      this->size = size;
    }
    void sportscar::init(int color, int size){
      this->color = color;
      this->size = size;
    }
4

3 回答 3

9

您需要做的就是不在实现中命名它们:

void car::init(int /* color */, int size){
    this->size = size;
}
于 2013-11-28T21:09:02.197 回答
1

您可以省略函数参数的名称。

void car::init(int, int size) {
  this->size = size;
}

这有时是不可取的,因为某些工具使用签名来提取文档,并且您可以内联定义函数。然后你可以使用演员表。

struct car {
  void init(int color, int size) {
    (void)color; // prevent warning
    this->size = size;
  }
};

同时,请记住 C++ 类通常不需要 init 函数,因为这就是构造函数的用途。

于 2013-11-28T21:12:23.667 回答
0

无需命名函数参数:如果您不使用参数,只需将其名称去掉:

void car::init(int, int size) {
    this->size = size;
}
于 2013-11-28T21:09:25.713 回答