将一个类分离成头文件(.h)和源文件(.cpp)时遇到的问题

3

我尝试将一个类分成声明和定义两部分,感觉做得很好,但编译时出现了以下错误消息。我不知道问题出在哪里,但我认为可能与简单的语法规则有关。

错误信息

...         ...: g++ -o main.exe Dog.cpp main.cpp
Dog.cpp:11:6: error: no declaration matches 'void Dog::setName(int)'
 void Dog::setName(int name){
      ^~~
In file included from Dog.cpp:1:
Dog.h:10:8: note: candidate is: 'void Dog::setName(std::__cxx11::string)'
   void setName(string name);
        ^~~~~~~
Dog.h:6:7: note: 'class Dog' defined here
 class Dog{
       ^~~
Dog.cpp:23:5: error: no declaration matches 'int Dog::getAge()'
 int Dog::getAge(){
     ^~~
In file included from Dog.cpp:1:
Dog.h:11:10: note: candidate is: 'std::__cxx11::string Dog::getAge()'
   string getAge();
          ^~~~~~
Dog.h:6:7: note: 'class Dog' defined here
 class Dog{
       ^~~

以下是使用的文件: main.cpp

#include <iostream>
#include <string>
#include "Dog.h"
using namespace std;


//Functions



int main(){
  //Variables
  string userInput;

  //Code
  Dog dolly("Dolly", 3);

  cout<<dolly.getName();
  cout<<dolly.getAge();


  return 0;
}

Dog.h

#ifndef DOG_H
#define DOG_H
#include <string>
using namespace std;

class Dog{
public:
  Dog(string name, int age);
  string getName();
  void setName(string name);
  string getAge();
  void setAge(int age);
private:
  int Age;
  string Name;
protected:

};


#endif // DOG_H

Dog.cpp

#include "Dog.h"
#include <iostream>
#include <string>
using namespace std;

Dog::Dog(string name, int age){
  setName(name);
  setAge(age);
};

void Dog::setName(int name){
  Name = name;
};

string Dog::getName(){
  return Name;
};

void Dog::setAge(int age){
  Age = age;
};

int Dog::getAge(){
  return Age;
};

感谢您提前回答!


string getAge()int Dog::getAge(),以及 setName 的相同之处。 - Mike Lui
1个回答

2
错误信息非常明确。
您的函数签名不匹配。
在您的头文件中声明了:
void setName(string name);

但是在你的实现文件中,你有

void Dog::setName(int name)

同样的问题出现在getAge上。签名不匹配。


哦,好的,当然,谢谢。我不知道我怎么会忽略那个。看来今天不是我的日子。 - samu_242

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接