2011-11-17 8 views
2

私は、次のC++クラスがあります:あなたが見ることができるようにC++のnoob - クラススコープ

class Eamorr { 
public: 
     redispp::Connection conn; 

     Eamorr(string& home, string& uuid) 
     { 
      //redispp::Connection conn("127.0.0.1", "6379", "password", false); //this works, but is out of scope in put()... 
      conn=new redispp::Connection("127.0.0.1", "6379", "password", false); //this doesn't work ;(
     } 
     put(){ 
      conn.set("hello", "world"); 
     } 
     ... 
} 

を、私はconnput()方法でコンストラクタと利用可能に初期化することにしたいです。

どうすればいいですか?事前に

多くのおかげで、

答えて

8

これは、メンバー初期化リストが何のためにあるのかです::(これを含む)の後

Eamorr(string& home, string& uuid) 
    : conn("127.0.0.1", "6379", "password", false) 
{ 
    //constructor body! 
} 

構文メンバーinitiazationリストを形成しています。ここでメンバを初期化することができます。各メンバはコンマで区切ります。ここで

は精巧な例である:ちょうどナワズの答えに展開する

+1

これは機能します!どうもありがとうございます! – Eamorr

0

:詳細については

struct A 
{ 
    int n; 
    std::string s; 
    B *pB; 

    A() : n(100), s("some string"), pB(new B(n, s)) 
    { 
     //ctor-body! 
    } 
}; 

、これらを参照してください。

実際に間違っていたことは、ポインタではない変数にnewを使用したことでした。変数connはポインタではないので、次のように書くことができます:

Eamorr(string& home, string& uuid) 
{ 
    conn = redispp::Connection("127.0.0.1", "6379", "password", false); 
}