【问题标题】:what is the reason of this error?这个错误的原因是什么?
【发布时间】:2014-12-30 16:27:39
【问题描述】:

在我的代码中,我想使用 Album 类的 get_title() 方法,但如果我在 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 类的方法?

客户.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;
        }
    }
}

购买.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

专辑.h:

#ifndef ALBUM_H
#define ALBUM_H

class Song;

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

客户.h:

#ifndef CUST_H
#define CUST_H

class Purchase;

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

#endif

歌曲.h:

#ifndef SONG_H
#define SONG_H

class Album;

class Song{
// . . .

private:
    Album* album;
};

#endif

【问题讨论】:

  • 请分享 customer.h 代码
  • @GaneshKamath 请不要。共享更多代码并没有使这个问题变得更好(我怀疑甚至更糟)。
  • 但我至少可以编译并检查是否可以针对这个章节进行改进
  • @GaneshKamath "但我至少可以编译和检查..." 通常不值得这样做。 OP 负责首先提供minimal example,我们可以使用它来重现此错误,并解释他们不清楚的地方。
  • 谢谢。我会记住这一点。

标签: c++ class pointers


【解决方案1】:

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

Album.h添加

#include "Song.h"

customer.cpp添加

#include "Album.h'

等等……

【讨论】:

  • 非常感谢。我只在 customer.cpp 中包含了 album.h 并且它有效。
猜你喜欢
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 2016-08-11
  • 1970-01-01
相关资源
最近更新 更多