43

私は C++ クラスに関する多くのチュートリアルを読んできましたが、他のチュートリアルに含まれているものを見逃しています。

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

4

4 に答える 4

33

十分に文書化された例は、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;
}
于 2009-05-14T21:41:51.877 に答える
13

彼が学生であっても、少なくともC ++の新しい訪問者にとっては複雑で簡単ではないため、答えてみる価値があります:)

C++ のクラスは、2 つの設計パラダイムの交差点として機能します。

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

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 の最も基本的なスケルトンです... もちろん、パブリック領域を無視することで、より簡単にすることができます! アクセス修飾子 (パブリック、プライベート) を消去すると、すべてがプライベートになります。しかし、それはナンセンスです。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 変数を想像してください。その関数は「fun」と呼ばれ、

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

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

魔法の行が表示されます。ここで、必要なことをコンパイラーに伝えることができます! すべてのことを行った後、関数のように NewDataType がローカルスコープで役に立たなくなったら、それを殺します。古典的な例は、「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」は少なくとも概念上は「double」であるため、「int」は「double」の太陽です :)

于 2009-06-26T02:29:23.580 に答える
10
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() {}
};
于 2009-05-14T21:40:53.127 に答える
8
#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;
}

ばかげていますが、そこにあります。「可視性」は誤称であることに注意してください: パブリックおよびプライベート コントロールのアクセス可能性ですが、「プライベート」なものでさえも外部から「可視」であり、アクセスできないだけです(アクセスしようとするとエラーになります)。

于 2009-05-14T21:42:45.553 に答える