C ++没有合适的默认构造函数可用

时间:2012-03-12 00:22:35

标签: c++ constructor c++-cli

我对C#有一些经验,但C ++语法和程序构造会产生一些问题。 我使用的是Visual C ++ 2008.首先为什么会出现这个错误?:

  

1> ...... \ Form1.h(104):错误C2512:   'Cargame :: Car':没有合适的默认构造函数

其次,为什么这条线不可能? // System :: Drawing :: Color color;

  

错误C3265:无法在非托管“汽车”中声明托管“颜色”

Form1.h包含:

namespace Cargame {
    using namespaces bla bla bla

    class Car;

    public ref class Form1 : public System::Windows::Forms::Form
    {
    public:
        Form1(void)
        {
            InitializeComponent();
        }
    Car* car;

        protected:
    ~Form1()
    {
        if (components)
        { delete components; }
    }

SOME MORE AUTOMATICALLY GENERATED CODE

    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
                 panel1->BackColor = System::Drawing::Color::Green;
                 car = new Car();
                 //car->draw();
             }
    };
}

Car.h的内容:

class Car
{
private:
        int speed;
        //System::Drawing::Color color;

public:
        Car();
};

Car.cpp的内容

#include "stdafx.h"
#include "Car.h"
#include "Form1.h"
#include <math.h>

//extern TForm1 *Form1;

Car::Car()
{
        speed = 0;
}

void Car::draw()
{
//implementation
}

3 个答案:

答案 0 :(得分:1)

要解决错误C2512,您需要添加:

#include "Car.h"

到Form1.h。

答案 1 :(得分:1)

将类Car的定义放在与其前向声明相同的命名空间中。

e.g。

Car.h的内容:

namespace Cargame {
class Car
{
private:
        int speed;
        //System::Drawing::Color color;

public:
        Car();
};
}

Car.cpp的内容

#include "stdafx.h"
#include "Car.h"
#include "Form1.h"
#include <math.h>

//extern TForm1 *Form1;
using namespace Cargame;
Car::Car()
{
        speed = 0;
}

void Car::draw()
{
//implementation
}

答案 2 :(得分:1)

非托管代码错误是因为您认为是非托管指针。

尝试Car ^ car我认为这是正确的语法。

您需要将班级定义为ref class Car