instanceofに相当するC++
C ++には、1つのオブジェクトが何らかのクラスタイプのインスタンスであるかどうかをチェックする直接的なメソッドがありません。 Javaでは、この種の機能を利用できます。
C ++ 11では、is_base_of
「instanceof」に似た最も近い機能は、 dynamic_cast
サンプルコード
#include <iostream>
using namespace std;
template<typename Base, typename T>
inline bool instanceof(const T *ptr) {
return dynamic_cast<const Base*>(ptr) != nullptr;
}
class Parent {
public:
virtual ~Parent() {}
virtual void foo () { std::cout << "Parent\n"; }
};
class Child : public Parent {
public:
virtual void foo() { std::cout << "Child\n"; }
};
class AnotherClass{};
int main() {
Parent p;
Child c;
AnotherClass a;
Parent *ptr1 = &p;
Child *ptr2 = &c;
AnotherClass *ptr3 = &a;
if(instanceof<Parent>(ptr1)) {
cout << "p is an instance of the class Parent" << endl;
} else {
cout << "p is not an instance of the class Parent" << endl;
}
if(instanceof<Parent>(ptr2)) {
cout << "c is an instance of the class Parent" << endl;
} else {
cout << "c is not an instance of the class Parent" << endl;
}
if(instanceof<Child>(ptr2)) {
cout << "c is an instance of the class Child" << endl;
} else {
cout << "c is not an instance of the class Child" << endl;
}
if(instanceof<Child>(ptr1)) {
cout << "p is an instance of the class Child" << endl;
} else {
cout << "p is not an instance of the class Child" << endl;
}
if(instanceof<AnotherClass>(ptr2)) {
cout << "c is an instance of AnotherClass class" << endl;
} else {
cout << "c is not an instance of AnotherClass class" << endl;
}
} 出力
p is an instance of the class Parent c is an instance of the class Parent c is an instance of the class Child p is not an instance of the class Child c is not an instance of AnotherClass class
-
C++での多重継承
多重継承は、クラスが複数の基本クラスから継承する場合に発生します。したがって、クラスは、多重継承を使用して複数の基本クラスから機能を継承できます。これは、C++などのオブジェクト指向プログラミング言語の重要な機能です。 多重継承を示す図を以下に示します- C++で多重継承を実装するプログラムは次のとおりです- 例 #include <iostream> using namespace std; class A { public: int a = 5; A() { &
-
C#のBigIntegerクラス
BigIntegerを使用して、C#で大きな数値を処理します。 BigIntegerに追加するアセンブリはシステムです。数値。 C#では、大きな整数はSystem.Numerics.BigIntegerにあります。 構文 BigIntegerの構文- [SerializableAttribute] public struct BigInteger : IFormattable, IComparable, IComparable<BigInteger>, IEquatable<BigInteger> サンプルコードスニペットを見てみましょう- BigInteger n