无法在CLR C ++中创建虚拟类

时间:2015-10-07 17:27:58

标签: c++ visual-studio-2010 clr virtual

我正在解决简单的程序在MSVS 2010这是Windows表单应用程序,突然遇到了非常奇怪的问题:我无法在课堂上创建虚函数。

以下是代码:

#pragma once;
#include <string>

using namespace std;
using namespace System;
class Reptile
{
    private:
    char *diet;
    string title;
    double weight;
    int lifespan;
    char sex;

public:

   char* getDiet();

   bool setDiet(char* newDiet);

string getTitle();
bool setTitle(string newTitle);

double getWeight();
bool setWeight(double newWeight);

int getLifespan();
bool setLifeSpan(int newLifespan);

char getSex();
void setSex(char newSex);

virtual void Show(void);
virtual void Voice(void);
~Reptile();
Reptile(); };

它会抛出这样的错误:

  

Reptile.obj:错误LNK2028:未解析的令牌(0A00000E)“public:virtual void __clrcall Reptile :: Voice(void)”(?Voice @ Reptile @@ $$ FUAMXXZ)在函数“void __clrcall dynamic initializer for”中引用const Reptile :: vftable'''(void)“(??? __ E ?? _ 7Reptile @@ 6B @@@ YMXXZ @?A0xc2bc2ccd @@ $$ FYMXXZ)

我真的无法弄清楚如何处理它,因为我对clr和东西不是很熟悉。

1 个答案:

答案 0 :(得分:0)

包括Show(),Voice(),Reptile()和~Reptile()的实体,它会起作用。像那样:

virtual void Show() {};
virtual void Voice() {};
Reptile() {};
~Reptile() {};

您可以在下面看到一个工作示例:

#include <iostream>
#include <string>

using namespace std;

class Reptile
{
private:
    char* diet;
    string title;
    double weight;
    int lifespan;
    char* sex;

public:
    char* getDiet()
    {
        return diet;
    };

    void setDiet(char* newDiet)
    {
        diet = newDiet;
    };

    string getTitle()
    {
        return title;
    }

    void setTitle(string newTitle)
    {
        title = newTitle;
    }

    double getWeight()
    {
        return weight;
    }

    double setWeight(double newWeight)
    {
        weight = newWeight;
    }

    int getLifespan()
    {
        return lifespan;
    }

    void setLifeSpan(int newLifespan)
    {
        lifespan = newLifespan;
    }

    char* getSex()
    {
        return sex;
    }

    void setSex(char* newSex)
    {
        sex = newSex;
    }

    // make them pure virtual functions
    virtual void Show() = 0;
    virtual void Voice() = 0;

    Reptile() {};
    ~Reptile() {};
};

class Dinosaur : public Reptile
{
public:
    virtual void Show()
    {
        cout << "Showing dino" << endl;
    }

    virtual void Voice()
    {
        cout << "Rawrrrrr!" << endl;
    }
};

int main()
{
    Reptile *dino1 = new Dinosaur();
    dino1->setSex("M");
    dino1->setTitle("T-Rex");

    cout << "Type: " << dino1->getTitle() << endl;
    cout << "Sex: " << dino1->getSex() << endl;
    dino1->Show();
    dino1->Voice();

    delete dino1;
}