C++ no appropriate default constructor available

谁说胖子不能爱 提交于 2019-12-11 02:00:53

问题


I have some experience with C# but C++ syntax and program construction makes some problems. I am using Visual C++ 2008. Firstly why is there this error?:

1>......\Form1.h(104) : error C2512: 'Cargame::Car' : no appropriate default constructor available

Secondly, why is not this line possible? //System::Drawing::Color color;

error C3265: cannot declare a managed 'color' in an unmanaged 'Car'

Form1.h contains:

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();
             }
    };
}

Contents of Car.h:

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

public:
        Car();
};

Contents of 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
}

回答1:


To resolve error C2512 you need to add:

#include "Car.h"

to Form1.h.




回答2:


Place the definition of a class Car in the same namespace as its forward declaration has been placed.

e.g.

Contents of Car.h:

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

public:
        Car();
};
}

Contents of 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
}



回答3:


The unmanaged code error is because you declared a unmanaged pointer, I think.

Try Car ^ car I think that is the right syntax.

And you need to define your class as ref class Car



来源:https://stackoverflow.com/questions/9660314/c-no-appropriate-default-constructor-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!