【问题标题】:Can't create virtual class in CLR C++无法在 CLR C++ 中创建虚拟类
【发布时间】:2016-01-05 01:37:45
【问题描述】:

我正在使用 Windows 窗体应用程序 MSVS 2010 中的简单程序,突然遇到一个非常奇怪的问题:我无法在类中创建虚拟函数。

代码如下:

#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 : error LNK2028: unresolved token (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 和其他东西不是很熟悉。

【问题讨论】:

  • 你只展示了Voice()的声明。你也有实现吗?

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


【解决方案1】:

包括 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;
}

【讨论】:

  • 不客气!看看我编辑的例子。您忘记定义访问器函数。
猜你喜欢
  • 2012-10-20
  • 2014-02-09
  • 2014-04-18
  • 2018-11-19
  • 2020-10-08
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多