C ++内部类没有编译

时间:2012-03-30 07:09:21

标签: c++ class inner-classes

我有一个名为Song的Class with Inner class Creator。下面是Song.h文件。请忽略这些评论。

#ifndef SONG_H
#define SONG_H
#include <iostream>


class Song
{
    public:
    class Creator{

        public:
        //Creator& name(const std::string name){};
       void  name(const std::string name){};

        //std::string getName(){};
    };


    private:
    std::string mName;
};

#endif // SONG_H

这里是Song.cpp类

#include "Song.h"

using std::string;
//using Song::Creator;
//Song::Creator& Song::Creator::name(const string name)
void Song::Creator::name(const string name)
{
  mName=name;
  std::cout<<name;
  //return *this;
}

//string Creator::getName()
//{
  //return mName;
//}

和主要课程

#include <iostream>
#include "Song.h"

int main()
{
Song::Creator sc;
sc.name("vickey");
//std::cout<<sc.getName();

return 0;
}

编译时抛出

/home/vickey/qtprojects/innerClass-build-desktop-Desktop_Qt_4_8_0_for_GCC__Qt_SDK__Release/../innerClass/Song.cpp:6: error: redefinition of 'void Song::Creator::name(std::string)'

如果我将名称功能更改为

void Creator::name(const string name)
{
  mName=name;
  std::cout<<name;
  //return *this;
}

我收到此错误

/home/vickey/qtprojects/innerClass-build-desktop-Desktop_Qt_4_8_0_for_GCC__Qt_SDK__Release/../innerClass/Song.cpp:6: error: 'Creator' has not been declared

我做错了什么?提前谢谢。

1 个答案:

答案 0 :(得分:6)

从类声明中删除定义:

void  name(const std::string name){};

更改为

void  name(const std::string name);

{}表示定义。