LoginSignup
5
2

More than 5 years have passed since last update.

勝手に他のクラスのプライベートメンバ変数を操作する

Posted at

C++で、他のクラスや提供されたライブラリ内のクラスのプライベートメンバを勝手に変更する方法。
テンプレート特殊化をクラス定義外から定義可能なことを利用する。

#include "stdafx.h"
#include <iostream>

class A{};
class Human {

private:
    int height = 175;
    int weight = 60;

public:

    template <class A>
    void printSize(A a){
        std::cout << height + weight << std::endl;
    }
};

// プライベートメンバをコピーするためのクラス.
class MyHuman{
public:
    int *height;
    int *weight;
};
MyHuman mh; // グローバルに宣言.


// 外部からテンプレート特殊化を行うことでプライベートメンバを操作できる.
class B{};
template <>
void Human::printSize(B b) {
    // 自分で作成したグローバルクラスに勝手にアドレスを代入してしまう.
    mh.height = &height;
    mh.weight = &weight;
}

int _tmain(int argc, char* argv[])
{
    Human h;
    A a;
    B b;

    // まずは通常のメソッドを呼ぶ.
    h.printSize(a);

    // 勝手に特殊化したメソッドを呼び、プライベートメンバーをグローバルオブジェクトmhに密かにコピーする.
    h.printSize(b);

    // ここからはに煮るなり焼くなりmhの値を好きに操作できる。

    // ポインタ経由で操作する.
    *(mh.height) = 100;
    *(mh.weight) = 100;

    // 値が書き換わっていることを確認する.
    h.printSize(a);

    return 0;
}

参考
[闇夜のC++]

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2