加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C错误:没有适当的默认构造函数可用

发布时间:2020-12-16 09:38:59 所属栏目:百科 来源:网络整理
导读:我知道这是经常被问到的问题,但是我无法找到让我的代码工作的方法,所以我很乐意得到一些帮助.这是代码: #include "stdafx.h"#include "iostream"#include "string"#include "cmath"#include "ctime"using namespace std;class quad{ int Lice;public: quad(
我知道这是经常被问到的问题,但是我无法找到让我的代码工作的方法,所以我很乐意得到一些帮助.这是代码:

#include "stdafx.h"
#include "iostream"
#include "string"
#include "cmath"
#include "ctime"
using namespace std;
class quad{
    int Lice;
public:
    quad(int x,int z){
       Lice = x*z;
    }
    int ShowLice(){
        return Lice;
    }
};
class tri : public quad{
    int Lice;
public:
    tri(int a,int b,int c){
        Lice = a*b*c;
    }

};
int main(){
quad ob1(2,2);
tri ob2(2,2,2);
cout<<ob1.ShowLice();
cout<<ob2.ShowLice();

return 0;
}

我使用VS2008,编译器的错误是:

project1.cpp(20) : error C2512: 'quad' : no appropriate default constructor available

谢谢,Leron.

解决方法

将其更改为

class quad{
protected:
    int Lice;
public:
    quad(int x,int z){
       Lice = x*z;
    }
    int ShowLice(){
        return Lice;
    }
};
class tri : public quad{

public:
    tri(int a,int c) : quad(a,b) {
        Lice *= c;
    }

};

在派生类和基类中都没有Lice成员.使其受到保护,以便派生类和子类重用相同的字段.

如果在基类中有非默认构造函数,则必须使用派生类构造函数中的正确参数调用基类构造函数,如上所示.

此外,如果您使用继承,最好在基类中提供virtual destructor.您的示例代码中可能不会出现此问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读