[英]Problem with separating a class into header (.h) and source (.cpp) file
所以我嘗試將 class 分為聲明和防御,我認為我做得很好,但是當我嘗試編譯它時,我收到了這個錯誤消息。 我看不出問題出在哪里,但我懷疑它與簡單的語法規則有關。
錯誤信息
... ...: 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
狗.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;
};
提前感謝您的回答!
錯誤信息非常清楚。
您的 function 簽名不匹配。
在你的 header 你聲明
void setName(string name);
但是在您的實現文件中,您有
void Dog::setName(int name)
與getAge
相同的問題。 簽名不匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.