有或没有用C++包装的类

With or without class wrappered in C++

本文关键字:包装 C++ 有用      更新时间:2023-10-16

我有一个基本问题,因为我已经有一段时间没有使用C++了。

我有一个这样的头文件:

它将保持不变,但是cpp文件将更改

#ifndef DOG_H_
#define DOG_H_
class Dog : Animal {
private:
    std::string breed;
public:
    Dog(std::string name, int age, std::string);
};

#endif /* DOG_H_ */

然后是CPP版本1:

#include "Dog.h"

Dog::Dog(std::string name, int age, std::string breedIn){
        Animal(name, age);
        breed = breedIn;
    }

或CPP版本2:

#include "Dog.h"
class Dog{

Dog::Dog(std::string name, int age, std::string breedIn){
        Animal(name, age);
        breed = breedIn; // the var name breed does not resolve
    }
};

版本1和版本2之间的区别在于,第二个版本被封装在class定义中。

为什么我要做一个而不做另一个。

其次,在第二个版本中,变量名bread没有解析。为什么?

Q:在第二个版本中,变量名bread不解析。为什么?

A: 因为这是错误的。

声明您的类一次,例如在标头中。

您可以在内联(在声明类时,在标头本身中)或在单独的.cpp中(如示例1中所做的那样)定义方法实现。这些链接可能有助于进一步解释:

  • http://www.cplusplus.com/doc/tutorial/classes/

  • http://www.cprogramming.com/declare_vs_define.html