简体   繁体   English

.cpp 文件中纯虚函数的正确返回值应该是多少?

[英]What should be the correct return value of a pure virtual function in .cpp file?

I am new in C++ and have a basic question.我是 C++ 新手,有一个基本问题。 My program has a header file and a .cpp one as well.我的程序也有一个头文件和一个 .cpp 文件。 In the header file there are two functions:在头文件中有两个函数:

int getSize() const = 0;
string getName() const = 0;

and in the corresponding part of the .cpp file:并在 .cpp 文件的相应部分:

int Class1::getSize() const { return 0;};
string Class1::getName() const {return "";};

What should I use inside the body of each function in .cpp file?我应该在 .cpp 文件中每个函数的主体内部使用什么? As these two functions are overwritten in the derived classes, can I put anything in the body of the classes in the .cpp file?由于这两个函数在派生类中被覆盖,我可以在 .cpp 文件中的类主体中放置任何内容吗? for example can I leave their bodies empty?例如,我可以让他们的身体空着吗? (although I receive warning messages) or use null for string or any other values for each. (尽管我收到警告消息)或对字符串使用 null 或对每个字符串使用任何其他值。 I am looking for a standard and correct way of doing it.我正在寻找一种标准且正确的方法。 Thanks.谢谢。

For pure virtual functions, you can omit the definition altogether.对于纯虚函数,您可以完全省略定义。 There are exceptions, when you must give a definition:有例外,当您必须给出定义时:

  • pure virtual destructors (because destructors of derived classes will call it)纯虚析构函数(因为派生类的析构函数会调用它)
  • if you call a pure virtual function (for example, from a function of a derived class)如果调用纯虚函数(例如,从派生类的函数中调用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM