【问题标题】:Not able to call base class constructor from dericed class with parameter in c++无法在 C++ 中使用参数从派生类调用基类构造函数
【发布时间】:2016-10-08 05:00:29
【问题描述】:

我在 DEV c++ 中的 c++ 中有以下场景

class base{
    int i=0;
    public:
         base(){
            cout<<"base default constructor"<<endl;
         }
         base(int i){
             cout<<"base with int"<<endl;
         }
};

class derive : public base{
    int j;
    public:
        derive(){
            cout<<"derive default";
        }
        derive(int i){
            int k=5;
            base(k);//////error 
            cout<<"derived with int "<<i<<endl;
        }
        void fun(int i){
            cout<<"finction "<<i<<endl;
        }
};
int main()
{
    derive d(9);

}

运行后出现以下错误
[错误] 声明“base k”冲突
[错误]“k”之前的声明为“int k”
为什么会出现此错误。
当我使用派生构造函数中声明的任何参数调用 base(5) 时,它工作正常。
提前致谢。

【问题讨论】:

  • "DEV c++" 不是编译器。
  • 嗨,是的,它是临时的,我没有初始化构造函数。但我想知道为什么 base(5) 或 base(j) 在 derived() 中有效,但在 base(i) 中无效。

标签: c++ inheritance constructor visibility derived-class


【解决方案1】:

如果在隐式参数上调用派生类中的基构造函数,则需要在field initialization list 中完成,如下所示:

    derive(int i) : base(i) {
        cout<<"derived with int "<< i <<endl;
    }

live demo

【讨论】:

    【解决方案2】:

    main()

        base b(3);
        derive d(9);
        base b1(2);
    

    //创建显式对象并传递整数参数。然后尝试 还可以在派生->基中传递特定的整数值。 在派生中

    base(8);
    

    并且总是打印在程序中行为怪异的变量的值

    【讨论】:

      【解决方案3】:
      #include <iostream>
      
      using namespace std;
      
      class base{
      public:
          base(){
              cout<<"base default constructor"<<endl;
          }
          base(int i){
              cout<<"base with int "<<i<<endl;
          }
      };
      
      class derive : public base{
      
      public:
          int j;
          int k;
          derive(){
              cout<<"derive default\n";
          }
          derive(int i){
              k=5;
              base(this->k);//////error
              cout<<"derived with int "<<i<<endl;
          }
          void fun(int i){
              cout<<"finction "<<i<<endl;
          }
      };
      int main()
      {
          derive p(10);
      
      
      }
      

      【讨论】:

      • 请稍微解释一下这个答案。仅代码的答案大多没有多大价值。感谢你!继续努力!
      【解决方案4】:

      对于base(k) 的含义有两种解释:

      1. 可能是临时创建的
      2. 可以是变量声明:变量名可以在括号中

      在这两个选项中,编译器使用第二个选项:如果某事物可以是声明或表达式,则选择声明。这与most vexing parse 有关,但不是那样。效果是在您使用base(k); 时尝试定义一个名为k 的变量,类型为base

      您可以使用以下之一来消除歧义

      1. (base(k));
      2. base{k};

      如果base 也有一个带有std::initializer_list&lt;int&gt; 的构造函数,那么这两个可能有不同的含义。

      【讨论】:

        猜你喜欢
        • 2015-08-18
        • 1970-01-01
        • 2016-07-19
        • 2011-03-05
        • 2011-05-03
        • 2018-07-21
        • 1970-01-01
        • 2014-11-27
        相关资源
        最近更新 更多