没有预定义的构造函数现有的C ++

时间:2014-12-07 20:47:48

标签: c++ class constructor

我花了好几个小时,但我似乎无法找到解决这个问题的方法。 我正在使用两个头文件,一个是Load.h,另一个是Source.h。

这是我的load.h:

#ifndef LOAD_H
#define LOAD_H
#include <string>
#include "Complexnumbersfrompreviousweek.h"
#include "Otherfunctionsfrompreviousweek.h"
#include "Source.h"

    class Load : public Source //I'm doing this to inherit the vs term
    {
    private:
        double load;
        double vload;
        double ApparentP;

    public:

        Load (double, double, double, double);
        double Calcvload (double, double, double, double);
    };
    #endif LOAD_H

这是我的Source.h:

#ifndef SOURCE_H
#define SOURCE_H
#include <string>
#include "Complexnumbersfrompreviousweek.h"
#include "Otherfunctionsfrompreviousweek.h"

class Source {
public:
    double vs;
    Source(double);

    double Ret(double);
};
#endif SOURCE_H

这是我的第二个.cpp文件:

#include "Line.h"
#include "Load.h"
#include "Source.h"
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iostream>
#include <math.h>

using namespace std;

Source::Source(double VoltageS)
{
    VoltageS = vs;
};
double Source::Ret(double vs)
{
    return vs;
}
Load::Load(double VoltageS, double Sl, double Z, double Vl)//Constructor
{
    Z = load;
    Sl = ApparentP;
    Vl = vload;
    VoltageS = vs;
};

我得到的错误是错误C2512:&#39;来源&#39;没有预定义的适当构造函数。

这就是我在main()中所做的事情:

Source Sorgente(VoltageS);
Load loadimpedance(VoltageS, Sl, Z, Vl);

所以基本上我正在创造&#34; Sorgente&#34;使用VoltageS作为参数的对象(由用户选择,我没有把这段代码放入),我试图将它分配给Vs,以便在后续加载的构造函数中使用它... < / p>

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

由于Load继承自Source,因此必须在其构造函数中构建Source库:

Load::Load(double VoltageS, double Sl, double Z, double Vl)//Constructor
{

由于您没有明确指定一个,编译器将自动插入默认值:

Load::Load(double VoltageS, double Sl, double Z, double Vl)//Constructor
: Source() // implicitly inserted by compiler
{

但是那个构造函数不存在 - 因此错误。要解决此问题,您需要显式调用正确的构造函数:

Load::Load(double VoltageS, double Sl, double Z, double Vl)//Constructor
: Source(VoltageS) // explicitly construct the base
{

无关紧要,在您的Source构造函数中,您指定了错误的元素:

Source::Source(double VoltageS)
{
    VoltageS = vs; // you are assigning to the temporary instead of your member
}

应该是:

Source::Source(double VoltageS)
: vs(VoltageS)
{ }