如何用C++编写一个简单的类?

Bab*_*ker 42 c++ constructor destructor public private-members

我一直在阅读很多关于C++类的教程,但是他们错过了其他教程所包含的内容.

有人可以告诉我如何编写和使用一个非常简单的C++类,它使用可见性,方法和一个简单的构造函数和析构函数?

TSt*_*per 32

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 或者更应该是SetBirthday()然后是GetAge(). (5认同)
  • 此外,由于这是一个学习样本,因此访问者应该标记为常量,因为它不会改变对象的内容. (4认同)
  • 讨厌得到/设置在这里.允许滥用猫.您不应该设置年龄(因为它可能设置得更年轻),但您应该能够增加年龄. (3认同)

Ara*_*raK 13

即使他是一名学生,也值得尝试回答,因为它是一个复杂的,至少对于一个新的C++访客而言并不那么容易:)

C++中的类服务于两种设计范例的交集,

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.
.
.
.
};
Run Code Online (Sandbox Code Playgroud)

这是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.
Run Code Online (Sandbox Code Playgroud)

上面几行的每一行都是一个声明,变量在那里构造.

最后想象一下函数中的上述int变量,该函数被称为'fun',

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

    return (m + z + y)
    // the magical line.
}
Run Code Online (Sandbox Code Playgroud)

你看到了神奇的线条,在这里你可以告诉编译器你想要的任何东西!在你完成所有事情并且你的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;
};
Run Code Online (Sandbox Code Playgroud)

现在这是最基本的框架,开始构建一个有用的类,你必须提供公共功能.

在C++中构建类时需要考虑很多小工具,

....

2)Object ::这意味着基本上是一种新类型,但区别在于它属于兄弟,姐妹,祖先和后代.在C++中看'double'和'int','int'是'double'的太阳,因为每个'int'至少在概念上是'double':)


180*_*ION 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() {}
};
Run Code Online (Sandbox Code Playgroud)


Ale*_*lli 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;
}
Run Code Online (Sandbox Code Playgroud)

傻,但是,你有.请注意,"可见性"是一个误称:公共和私人控制可访问性,但即使是"私有"的东西仍然是从外部"可见",只是无法访问(尝试访问它是一个错误).

  • "const string&name"表示不执行复制,"string name"告诉编译器复制.为什么在不需要副本时要求复印件?这是一个很好的习惯,当你以只读方式使用它们时,通过const ref传递args(不是简单的值类型,如int,指针等). (2认同)