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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/865922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:39:48  来源:igfitidea点击:

How to write a simple class in C++?

c++constructordestructorpublicprivate-members

提问by Babiker

I have been reading a lot of tutorials on C++ class but they miss something that other tutorials include.

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

Can someone please show me how to write and use a very simple C++ class that uses visibility, methods and a simple constructor and destructor?

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

回答by TStamper

Well documented example taken and explained better from Constructors and Destructors in C++:

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;
}

回答by AraK

Even if he is a student, worth trying to answer because it is a complex one not that easy at least for a new Visitor of C++ :)

即使他是一名学生,也值得尝试回答,因为这是一个复杂的问题,至少对于 C++ 的新访问者来说并不容易:)

Classes in C++ serve an intersection of two design paradigms,

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

1) ADT :: which means basically a new type, something like integers 'int' or real numbers 'double' or even a new concept like 'date'. in this case the simple class should look like this,

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.
.
.
.
};

this is the most basic skeleton of an ADT... of course it can be simpler by ignoring the public area! and erasing the access modifiers (public, private) and the whole thing will be private. but that is just nonsense. Because the NewDataType becomes useless! imagine an 'int' that you can just declare but you CAN NOT do anything with it.

这是一个ADT最基本的骨架……当然可以忽略公共区域更简单!并删除访问修饰符(公共,私有),整个事情将是私有的。但这只是无稽之谈。因为 NewDataType 变得没用了!想象一个你可以声明但你不能用它做任何事情的“int”。

Then, you need some useful tools that are basically not required to the existence of the NewDataType, but you use them to let your type look like any 'primitive' type in the language.

然后,您需要一些有用的工具,这些工具对于 NewDataType 的存在基本上不是必需的,但是您可以使用它们让您的类型看起来像语言中的任何“原始”类型。

the first one is the Constructor. The constructor is needed in many places in the language. look at int and lets try to imitate its behavior.

第一个是构造函数。语言中的许多地方都需要构造函数。看看 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.

every line of the above lines is a declaration, the variable gets constructed there.

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

and in the end imagine the above int variables in a function, that function is called 'fun',

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

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

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

you see the magical line, here you can tell the compiler any thing you want! after you do every thing and your NewDataType is no more useful for the local scope like in the function, you KILL IT. a classical example would be releasing the memory reserved by 'new'!

你看到了神奇的一行,在这里你可以告诉编译器你想要的任何东西!在你做完每一件事并且你的 NewDataType 对函数中的局部范围不再有用之后,你杀死它。一个经典的例子是释放'new'保留的内存!

so our very simple NewDataType becomes,

所以我们非常简单的 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;
};

Now this is the very basic skeleton, to start building a useful class you have to provide public functions.

现在这是非常基本的骨架,要开始构建有用的类,您必须提供公共函数。

there are A LOT of tiny tools to consider in building a class in C++,

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

. . . .

. . . .

2) Object :: which means basically a new type, but the difference is that it belongs to brothers, sisters, ancestors and descendants. look at 'double' and 'int' in C++, the 'int' is a sun of 'double' because every 'int' is a 'double' at least in concept :)

2) Object :: 基本上是一个新的类型,但不同的是它属于兄弟姐妹,祖先和后代。看看 C++ 中的“double”和“int”,“int”是“double”的太阳,因为每个“int”至少在概念上都是“double”:)

回答by 1800 INFORMATION

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() {}
};

回答by Alex Martelli

#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;
}

Silly, but, there you are. Note that "visibility" is a misnomer: public and private control accessibility, but even "private" stuff is still "visible" from the outside, just not accessible(it's an error to try and access it).

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