2016-09-30 5 views
-4

こんにちは私はconst char *に奇妙な方法で同じ問題を抱えています。 Color :: Text()は静的char配列を返しますが、配列のconst char * pointerを初期化するためにも使用されます。Const char *奇妙な振る舞い

wtfもし私がrofl :: Defaultが実際に動作し、最新の "const char"にならないようにしたいのですか?Color :: Text?

#include <windows.h> 
class Color 
{ 
public: 
    int R; 
    int G; 
    int B; 
    int A; 
    Color(int r, int b, int g, int a = 255) 
    { 
    R = r; 
    G = g; 
    B = b; 
    A = a; 
    } 
    const char* Text() 
    { 
    static char Texts[124]; 
    snprintf(Texts, 124, "%i %i %i %i", R, G, B, A); 
    return Texts; 
    } 
} 
class rofl 
{ 
public: 
    const char* Default; 
    const char* Value; 
    rofl(const char* d) 
    { 
     Default = d; 
     Value = d; 
    } 
} 

rofl dood("0"); 
rofl doaaod(Color(0,0,0).Text()); 
rofl xxxx(Color(0,55,0).Text()); 

int main() 
{ 
    printf("%s %s\n", dood.Default, dood.Value); 
    printf("%s %s\n", doaaod.Default, doaaod.Value); 
    printf("%s %s\n", xxxx.Default, xxxx.Value); 
    return 0; 
} 

出力は次のようになります。

0 0 
0 55 0 0 0 0 
0 55 0 0 55 0 
+0

'rofl'のコンストラクタでは、' Default'と 'Value'が指すバッファ(例:演算子' new'を使用して)を作成します。次に、それらのバッファにデータをコピーします。さらに、 'char *'の代わりに 'std :: string'オブジェクトを使用すると、動的割り当てがきれいに管理されます。 – Peter

答えて

1

あなたは(離れてリテラル文字列から)あなたのコードで唯一の文字バッファを持っています。 const char*は文字バッファへのポインタであり、元のバッファの新しいバッファではありません。

したがって、Color :: Textを呼び出すたびに、同じ文字バッファー上に書き込んでおり、すべてのポインターが同じ文字を読み込むのは当然です。

CおよびC++ではポインタの概念を理解する必要があります。

この場合、C++では、必要な動作について、const char*のすべての使用をstd::stringに置き換える必要があります。

CアクセシビリティのC++を簡単に学ぶために、言語の古文な部分に入ることなく、「Accelerated C++」という本をお勧めします。

+0

std :: stringのようなゴミ箱を使うことはできません。 – Lolmelon

+1

@Lolmelon:あなたの質問には[tag:C++]というタグが付けられています。 C++を使用できない場合は、C++をタグ付けしないでください。 – IInspectable

+0

@Lolmelon: "ゴミ箱"? –