拡張オブジェクトをパラメーターとして関数に渡すときに抽象クラスを使用しようとしていますが、これまでの試行でいくつかのコンパイラ エラーが発生しました。
問題が何であるかについていくつかの手がかりがあります.抽象クラスをインスタンス化することは明らかに許可されていません.MyClassのコードの一部はこれを実行しようとしていると思いますが、これは私の意図ではありません. いくつかの調査では、目的を達成するためにオブジェクトをポインターとして参照する必要があることが示唆されていますが、これまでの試みは失敗しており、これが答えであるかどうかさえわかりません (したがって、ここで質問しています)。
私は C++ よりも Java に精通しているので、提出します。私の問題の一部はこれによるものだと確信しています。
これが私のプログラムでやろうとしていることの例です:
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;
}