这个错误的原因是什么?

时间:2014-12-30 16:27:40

标签: c++ class pointers

在我的代码中,我想使用get_title()类的Album方法,但如果我在customer.cpp中包含“album.h”,则会给我这个错误:

error C2036: 'Song *' : unknown size

但现在我有这个错误:

error C2227: left of '->get_title' must point to class/struct/union/generic type
error C2027: use of undefined type 'Album'
IntelliSense: pointer to incomplete class type is not allowed

如何访问Album类的方法?

customer.cpp:

#include "customer.h"

void Customer::print_tmpPurchase()
{
    if (tmpPurchase.get_albums().size() != 0)
    {
        cout << "Albums Of Your Basket: " << endl;
        for (int i = 0; i < tmpPurchase.get_albums().size(); i++)
        {
            cout << "\t" << i + 1 << "." << tmpPurchase.get_albums()[i]->get_title() << endl;
        }
    }
}

purchase.h:

#ifndef PURCH_H
#define PURCH_H

class Song;
class Album;

class Purchase{
public:
    vector <Song*> get_songs() { return songs; }
    vector <Album*> get_albums() { return albums; }
private:
    vector <Song*> songs;
    vector <Album*> albums;
};

#endif

album.h:

#ifndef ALBUM_H
#define ALBUM_H

class Song;

class Album{
public:
    string get_title() { return title; }
private:
    string title;
    vector <Song> songs;
};
#endif

customer.h:

#ifndef CUST_H
#define CUST_H

class Purchase;

class Customer{
public:
    void print_tmpPurchase();
private:
    Purchase tmpPurchase;
};

#endif

song.h:

#ifndef SONG_H
#define SONG_H

class Album;

class Song{
// . . .

private:
    Album* album;
};

#endif

1 个答案:

答案 0 :(得分:1)

问题是当您尝试访问实例的成员时,编译器不会看到类 definitions 。虽然您已经为类提供了前向声明,但这还不够。在访问这些类的成员或需要其大小的.cpp和.h文件中,您需要包含所有相应的标头,以便在使用时可以看到定义 。在这种情况下,您的Album类似乎需要Song的定义,而不仅仅是前向声明。

Album.h添加

#include "Song.h"

customer.cpp添加

#include "Album.h'

依旧......