One*_*ser 0 c++ polymorphism inheritance multiple-inheritance include
我目前正在编写一个程序,根据不同的参数搜索歌曲.在我的系统中有两种类型的歌曲:歌词和乐器.因为我需要将它们都放在1个向量中,所以我有一个歌曲类和一个LyricsSong&InstrumentalSong子类.
所以我有一个Song.h文件:
#include <stdio.h>
#include <iostream>
#include <string>
class Song
{
public:
std::string title;
virtual void print();
virtual void printSong(std::string query);
};
Run Code Online (Sandbox Code Playgroud)
还有乐器和歌词子类,它们以这种方式定义:
class LyricsSong : public Song
class InstrumentalSong : public Song
Run Code Online (Sandbox Code Playgroud)
两者都包括Song.h,在这两个类中,类只在头文件中定义.
当我尝试运行另一个使用这两个子类的文件时,包括:
#include "LyricsSong.h"
#include "InstrumentalSong.h"
Run Code Online (Sandbox Code Playgroud)
(显然更多的cpp库),我得到以下编译错误:
In file included from /cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/InstrumentalSong.h:16:0,
from /cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/songsParser.cpp:26:
/cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/Song.h:6:7: error: redefinition of 'class Song'
class Song
^
In file included from /cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/LyricsSong.h:15:0,
from /cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/songsParser.cpp:25:
/cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/Song.h:6:7: error: previous definition of 'class Song'
class Song
^
Run Code Online (Sandbox Code Playgroud)
什么时候:
我该怎么办?PS我没有导入任何cpp文件,只有头文件.
您必须告诉预处理器只包含一次头文件.您可以通过添加#pragma once所有*.h文件的顶部来实现:
#pragma once
//Your header file's code
Run Code Online (Sandbox Code Playgroud)
始终使用此行开始头文件也是一种很好的做法.
它们都包含'Song.h'文件和预处理器两次获取文件内容.您需要在#ifndef #define和#endif指令中编写'LyricsSong.h'和'InstrumentalSong.h'文件内容.像这样
#ifndef LYRICS_SONG_H
#define LYRICS_SONG_H
your code goes here.
...
#endif
Run Code Online (Sandbox Code Playgroud)