私はこのコードを持っていて、質問したいのですが、例外を取得せずに新しいint()でクラスオブジェクトを初期化するにはどうすればよいですか?オブジェクトの値を出力すると、ジャンクが出力されますが、この割り当てがどのように可能であるかがわかりません。new int(value)を使用すると、正確にはどうなりますか?int用のスペースを作成し、値で初期化しませんか?
class A {
static A* first;
static A* last;
A *prev, *next;
public:
A() : prev(last), next(nullptr) {
cout << "A ctor" << endl;
if (last) last->next = this;
last = this;
if (!first) first = this;
}
virtual ~A() {
if (prev) prev->next = next;
if (next) next->prev = prev;
if (first == this) first = next;
if (last == this) last = prev;
}
static void printAll() {
if (first) cout << *first;
else cout << "list is empty" << endl;
}
friend ostream& operator<<(ostream& out, const A&a) {
a.printSelf();
if (a.next) out << *(a.next);
else out << endl;
return out;
}
virtual void printSelf() const = 0;
};
template<class T>
class B : public A {
T * t;
public:
B(const T& _t) : t(new T(_t)) { cout << "B ctor" << endl; }
virtual ~B() {
cout << "Dtor B" << endl;
cout << *this;
delete t;
}
virtual void printSelf()const override {
cout << *t << ' ';
}
};
A* A::first = nullptr;
A * A::last = nullptr;
int main() {
B<int*>b1 = new int(5);
b1.printSelf(); //prints junk (b1.t value)
cout << endl;
cout << typeid(b1).name() << endl; //prints class B<int*>
}
あなたはおそらくexplicit
キーワードを探しています:
明示的でない場合、コンパイラーはコンストラクターを使用して型間の暗黙的な変換を試みます。
class Test
{
public:
Test(int){}
};
Test t = 42;
これが発生するはずがない場合は、を使用できますexplicit
(個人的には、コピー以外の単一引数のコンストラクターごとにデフォルトで使用することをお勧めします。
class Test
{
public:
explicit Test(int){}
};
Test t = 42; //error here
あなたの場合、T
はへのポインタint
であるため、new int(5)
ヒープ上に整数を生成し、それへのポインタを返します。これはの有効な引数ですB
。
コンストラクターの内部を見る:
B(const T& _t) : t(new T(_t)) { cout << "B ctor" << endl; }
_t
intへのポインタであるaを受け取り(例:0xabcd-> 5)、。this->t
で初期化されたintへのポインタへの新しいポインタで初期化し0xabcd
ます。あれは:
B(const int*& _t): t(new int*(_t))...
// t is &(0xabcd), *t is 0xabcd, **t is 5
次に印刷*t
:
cout << 0xabcd << ' '; // printing the memory address, not the value 5.
代わりにこれを試すことができます:
cout << **t << ' '; // Print 5
しかし...二重割り当てを解決し、メモリリークを取り除く方がおそらく良いでしょう:
B<int>b1 = 5;
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加