我已经浏览了网络并尝试了他们建议的大部分内容,但我仍然无法让我的代码工作。我有两个使用header files and .cpp files
创建的类我希望在不使用inheritance
的情况下在另一个类中包含一个类但我收到错误。
以下是Birthday class
的代码:
Birthday.h:
#ifndef BIRTHDAY_H
#define BIRTHDAY_H
class Birthday
{
public:
Birthday(int m, int d, int y);
~Birthday();
void printDate();
protected:
private:
int month;
int day;
int year;
};
#endif // BIRTHDAY_H
Birthday.cpp:
#include <iostream>
#include "Birthday.h"
using namespace std;
Birthday::Birthday(int m, int d, int y):month(m), day(d), year(y)
{
//ctor
}
Birthday::~Birthday()
{
cout << "Birthday Destructor" << endl;
}
void Birthday::printDate()
{
cout << month << "/" << day << "/" << year << endl;
}
然后是包含Birthday class as a member
Person类的类。
Person.h:
#ifndef PERSON_H
#define PERSON_H
#include "Birthday.h"
class Person
{
public:
Person(string n, Birthday b);
void printinfo();
protected:
private:
string name;
Birthday bd;
};
#endif // PERSON_H
Person.cpp:
#include <iostream>
#include <string>
#include "Birthday.h"
#include "Person.h"
using namespace std;
Person::Person(string n, Birthday b):name(n), bd(b)
{
//ctor
}
void Person::printinfo()
{
cout << name << endl;
bd.printDate();
}
请注意,当两个类在同一个文件中创建但在单独的头文件和源文件中使用时会出错。
错误讯息:
Person::Person(string n, Birthday b):name(n), bd(b)
^
In file included from /home/george/codeblock-docs/Birthday/Person.cpp:4:0:
/home/george/codeblock-docs/Birthday/Person.h:6:7: error: candidates are: constexpr Person::Person(Person&&)
class Person
^
/home/george/codeblock-docs/Birthday/Person.h:6:7: error: constexpr Person::Person(const Person&)
/home/george/codeblock-docs/Birthday/Person.h:6:7: error: Person::Person()
/home/george/codeblock-docs/Birthday/Person.cpp: In member function ‘void Person::printinfo()’:
/home/george/codeblock-docs/Birthday/Person.cpp:18:13: error: ‘name’ was not declared in this scope
cout << name << endl;
^
对不起是没有看到抱抱的通知我希望这更明确。编译代码时显示此错误
答案 0 :(得分:0)
std::
中string
没有Person.h
名称空间说明符。你应该专攻std::string
:
class Person
{
public:
Person(std::string n, Birthday b);