首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C++中使用抽象类

在C++中使用抽象类
EN

Stack Overflow用户
提问于 2009-03-16 11:53:59
回答 9查看 68.6K关注 0票数 16

在将扩展对象作为参数传递给函数时,我尝试使用抽象类,但到目前为止,我的尝试导致了一些编译器错误。

我有一些关于问题所在的线索,我显然不允许实例化抽象类,我相信MyClass中的一些代码正在尝试这样做,尽管这不是我的意图。一些研究建议我应该引用对象作为指针来实现我想要的东西,但是到目前为止我的尝试都失败了,我甚至不确定这是不是答案(因此我在这里问)。

我现在要提交的是,我更熟悉Java而不是C++,我确信我的问题的一部分是由于这一点。

下面是我在我的程序中尝试做的一个例子:

class A {
    public:
        virtual void action() = 0;
};

class B : public A {
    public:
        B() {}

        void action() {
            // Do stuff
        }
};

class MyClass {

    public:

        void setInstance(A newInstance) {
            instance = newInstance;
        }

        void doSomething() {
            instance.action();
        }

    private:

        A instance;
};

int main(int argc, char** argv) {
    MyClass c;
    B myInstance;
    c.setInstance(myInstance);
    c.doSomething();
    return 0;
}

这个示例产生的编译器错误与我在程序中得到的错误相同:

sean@SEAN-PC:~/Desktop$ gcc -o test test.cpp
test.cpp:20: error: cannot declare parameter ‘newInstance’ to be of abstract type ‘A’
test.cpp:2: note:   because the following virtual functions are pure within ‘A’:
test.cpp:4: note:   virtual void A::action()
test.cpp:30: error: cannot declare field ‘MyClass::instance’ to be of abstract type ‘A’
test.cpp:2: note:   since type ‘A’ has pure virtual functions
test.cpp: In function ‘int main(int, char**)’:
test.cpp:36: error: cannot allocate an object of abstract type ‘A’
test.cpp:2: note:   since type ‘A’ has pure virtual functions

更新

感谢大家的反馈。

我已经将"MyClass::instance“更改为包含一个类型为A的指针,但现在我得到了一些与vtable相关的奇怪错误:

sean@SEAN-PC:~/Desktop$ gcc -o test test.cpp
/tmp/ccoEdRxq.o:(.rodata._ZTI1B[typeinfo for B]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
/tmp/ccoEdRxq.o:(.rodata._ZTI1A[typeinfo for A]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
/tmp/ccoEdRxq.o:(.rodata._ZTV1A[vtable for A]+0x8): undefined reference to `__cxa_pure_virtual'
collect2: ld returned 1 exit status

我修改后的代码如下(A、B未修改):

class MyClass {

    public:

        void setInstance(A* newInstance) {
            instance = newInstance;
        }

        void doSomething() {
            instance->action();
        }

    private:

        A* instance;
};

int main(int argc, char** argv) {
    MyClass c;
    B myInstance;
    c.setInstance(&myInstance);
    c.doSomething();
    return 0;
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/650091

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档