2009-05-14 13 views
32

私はC++クラスで多くのチュートリアルを読んできましたが、他のチュートリアルには含まれていないものがあります。C++で簡単なクラスを書くには?

可視性、メソッド、および単純なコンストラクタとデストラクタを使用する非常に単純なC++クラスの記述方法を教えてください。

+30

これは宿題です! – xian

+7

私はその話題でグーグルで例を見つけることができなかったとはほとんど思えません。下の例のほとんどは、他のウェブのチュートリアルからここに貼り付けられたコピーだけです。 –

+7

あなたは真剣に見ていてはいけません。 –

答えて

8
class A 
{ 
    public: 
    // a simple constructor, anyone can see this 
    A() {} 
    protected: 
    // a simple destructor. This class can only be deleted by objects that are derived from this class 
    // probably also you will be unable to allocate an instance of this on the stack 
    // the destructor is virtual, so this class is OK to be used as a base class 
    virtual ~A() {} 
    private: 
    // a function that cannot be seen by anything outside this class 
    void foo() {} 
}; 
25

はまあ撮影した例を文書化し、Constructors and Destructors in C++からより良い説明:

#include <iostream>   // for cout and cin 

class Cat      // begin declaration of the class 
{ 
    public:      // begin public section 
    Cat(int initialAge);  // constructor 
    Cat(const Cat& copy_from); //copy constructor 
    Cat& operator=(const Cat& copy_from); //copy assignment 
    ~Cat();     // destructor 

    int GetAge() const;  // accessor function 
    void SetAge(int age);  // accessor function 
    void Meow(); 
private:      // begin private section 
    int itsAge;    // member variable 
    char * string; 
}; 

// constructor of Cat, 
Cat::Cat(int initialAge) 
{ 
    itsAge = initialAge; 
    string = new char[10](); 
} 

//copy constructor for making a new copy of a Cat 
Cat::Cat(const Cat& copy_from) { 
    itsAge = copy_from.itsAge; 
    string = new char[10](); 
    std::copy(copy_from.string+0, copy_from.string+10, string); 
} 

//copy assignment for assigning a value from one Cat to another 
Cat& Cat::operator=(const Cat& copy_from) { 
    itsAge = copy_from.itsAge; 
    std::copy(copy_from.string+0, copy_from.string+10, string); 
} 

// destructor, just an example 
Cat::~Cat() 
{ 
    delete[] string; 
} 

// GetAge, Public accessor function 
// returns value of itsAge member 
int Cat::GetAge() const 
{ 
    return itsAge; 
} 

// Definition of SetAge, public 
// accessor function 
void Cat::SetAge(int age) 
{ 
    // set member variable its age to 
    // value passed in by parameter age 
    itsAge = age; 
} 

// definition of Meow method 
// returns: void 
// parameters: None 
// action: Prints "meow" to screen 
void Cat::Meow() 
{ 
    cout << "Meow.\n"; 
} 

// create a cat, set its age, have it 
// meow, tell us its age, then meow again. 
int main() 
{ 
    int Age; 
    cout<<"How old is Frisky? "; 
    cin>>Age; 
    Cat Frisky(Age); 
    Frisky.Meow(); 
    cout << "Frisky is a cat who is " ; 
    cout << Frisky.GetAge() << " years old.\n"; 
    Frisky.Meow(); 
    Age++; 
    Frisky.SetAge(Age); 
    cout << "Now Frisky is " ; 
    cout << Frisky.GetAge() << " years old.\n"; 
    return 0; 
} 
+2

ここでは嫌いを取得/設定します。猫の乱用を許します。年齢を設定することはできません(若年に設定される可能性があります)が、年齢を増やすことができます。 –

+2

または、SetBirthday()、GetAge()が必要です。 – Reunanen

+3

また、これは学習サンプルのためのものであるため、アクセサはオブジェクトの内容を変更しないため、定数としてマークする必要があります。 –

4
#include <iostream> 
#include <string> 

class Simple { 
public: 
    Simple(const std::string& name); 
    void greet(); 
    ~Simple(); 
private: 
    std::string name; 
}; 

Simple::Simple(const std::string& name): name(name) { 
    std::cout << "hello " << name << "!" << std::endl; 
} 

void Simple::greet() { 
    std::cout << "hi there " << name << "!" << std::endl; 
} 

Simple::~Simple() { 
    std::cout << "goodbye " << name << "!" << std::endl; 
} 

int main() 
{ 
    Simple ton("Joe"); 
    ton.greet(); 
    return 0; 
} 

愚かを、しかし、そこにあります。 「可視性」は誤った言い方です:公的および私的なコントロールのアクセシビリティですが、「プライベート」なものはまだ外部から「可視」であり、にアクセス可能ではありません(アクセスしようとするとエラーです)。彼はそれが、少なくともCでC++ :)

クラスの新しいビジター用の2つの設計パラダイムの交差点を果たす++ことは容易ではない複雑なものであるので、答えようとする価値学生、場合でも

+0

実際、可視性は問題を引き起こす可能性があります。コンパイラは、可視性に基づいて呼び出すオーバーロードされた関数と引数で最もよく一致する関数を選択し、アクセスできない関数を呼び出すことができます。これらの概念は混乱する可能性があります。 –

+0

Alexが文字列名の代わりに文字列&名前を使用した理由 – Babiker

+2

"const string&name"はコピーが実行されないことを意味し、 "string name"はコピーを作成するようにコンパイラに指示します。必要がないときにコピーを頼むのはなぜですか?獲得するのは良い習慣ですが、constやrefなどの単純な値型ではないargsを読み込み専用で使用するときに渡します。 –

10

1)ADT ::これは、基本的に整数型のint型や実数型のdouble型、さらには日付型のような新しい型の新しい型を意味します。単純なクラスは次のようになります。この場合 、

class NewDataType 
{ 
public: 
// public area. visible to the 'user' of the new data type. 
. 
. 
. 
private: 
// no one can see anything in this area except you. 
. 
. 
. 
}; 

本であるADTの最も基本骨格...もちろん は、それが公共のエリアを無視して単純にすることができます! とアクセス修飾子(public、private)を消去すると、すべてがプライベートになります。 しかしそれはちょうどナンセンスです。なぜなら、NewDataTypeは役に立たないからです! あなたが宣言することができますが、あなたはそれで何もできません 'int'を想像してください。

次に、基本的にNewDataTypeの存在に必須ではない便利なツールがいくつか必要ですが、それらを使用して、タイプをその言語の「プリミティブ」タイプのように見えるようにします。

最初のものはコンストラクタです。コンストラクタは言語の多くの場所で必要です。 intを見て、その動作を真似しようとします。

int x; // default constructor. 

int y = 5; // copy constructor from a 'literal' or a 'constant value' in simple wrods. 
int z = y; // copy constructor. from anther variable, with or without the sametype. 
int n(z); // ALMOST EXACTLY THE SAME AS THE ABOVE ONE, it isredundant for 'primitive' types, but really needed for the NewDataType. 

上記の行の各行は宣言であり、変数はそこに構築されます。

、最後に機能における上記int型の変数を想像し、その機能を「楽しい」と呼ばれ、

int fun() 
{ 
    int y = 5; 
    int z = y; 
    int m(z); 

    return (m + z + y) 
    // the magical line. 
} 

あなたは魔法の行を参照して、ここでは、コンパイラあなたが好きなものを伝えることができます! あなたがすべてのことをして、あなたのNewDataTypeが関数のようにローカルスコープには役に立たないなら、あなたはKILL ITです。 古典的な例では、 'new'によって予約されたメモリが解放されます!

はそう私たちの非常にシンプルなNewDataTypeは

class NewDataType 
{ 
public: 
// public area. visible to the 'user' of the new data type. 
    NewDataType() 
    { 
     myValue = new int; 
     *myValue = 0; 
    } 

    NewDataType(int newValue) 
    { 
     myValue = new int; 
     *myValue = newValue; 
    } 

    NewDataType(const NewDataType& newValue){ 

     myValue = new int; 
     *myValue = newValue.(*myValue); 
    } 
private: 
// no one can see anything in this area except you. 
    int* myValue; 
}; 

は今、これは公共の機能を提供するために、あなたが持っている有用なクラスの構築を開始するために、非常に基本骨格である、となります。

C++、

でクラスを構築する際に考慮すべき小さなツールがたくさんあります。 。 。 。

2)オブジェクト::基本的に新しいタイプを意味しますが、違いは兄弟、姉妹、祖先、子孫に属するという点です。 C + +で 'double'と 'int'を見ると、 'int'はすべて 'int'が少なくともコンセプトで 'double'なので、 'double'の太陽です:

関連する問題