【问题标题】:Problem with separating a class into header (.h) and source (.cpp) file将类分离为头文件 (.h) 和源文件 (.cpp) 的问题
【发布时间】:2020-04-05 14:20:07
【问题描述】:

所以我尝试将一个类分为声明和定义,我认为我做得很好,但是当我尝试编译它时,我收到了这个错误消息。我不明白问题出在哪里,但我怀疑它与一个简单的语法规则有关。

错误信息

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

狗.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 也一样

标签: c++ compilation header


【解决方案1】:

错误信息很清楚。

您的函数签名不匹配。

在你的标题中声明

void setName(string name);

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

void Dog::setName(int name)

getAge 的问题相同。签名不匹配。

【讨论】:

  • 哦,好的,当然,谢谢。不知道我是怎么看过去的。猜猜这不是我的日子
猜你喜欢
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多