【问题标题】:Trying to use referances to an object for another class试图使用对另一个类的对象的引用
【发布时间】:2013-01-17 13:25:06
【问题描述】:

我的问题是,我似乎无法通过引用将对象发送给另一个类。我在网上查到这个时运气不佳。如果可以,请检查我的来源,如果您有任何想法,请告诉我。 TYIA-罗兰

我也收到这些错误

 error: field 'PgmClass' has incomplete type
 error: 'PgmClass' does not name a type
 error: expected ')' before 'thesource'
 error: 'm_hereitis' was not declared in this scope

#include <iostream>
#include "pgmclass.h"
#include "inclobj.h"

int main()
{

    char catchcin[256];

    PgmClass wilko;

    wilko.addToSet( 7 );
    wilko.addToSet( 8 );
    wilko.addToSet( 9 );

    InclObj alpha( wilko );

    wilko.addToSet( 10 );
    wilko.addToSet( 11 );

    // This doesn't work
    alpha.eraseOne( 10 );

    // How can I get this to work using referances?

    std::cout << "Program Running." << std::endl;
    std::cin >> catchcin;

    return 0;
}


----------

#include <set>

class PgmClass  {

      public:
    int addToSet( int );
    bool eraseSet( int );
    std::set<int> m_userset;
};

int PgmClass::addToSet( int theint )    {

    m_userset.insert( theint );
}

bool PgmClass::eraseSet( int eraseint )  {

    m_userset.erase( eraseint );
}


----------

class InclObj   {

      public:
    InclObj( PgmClass );
    void eraseOne( int );

    PgmClass m_hereitis;
};

InclObj::InclObj( PgmClass thesource )    {

    m_hereitis = thesource;
}

void InclObj::eraseOne( int findint )    {

    m_hereitis.eraseSet( findint );
}

【问题讨论】:

  • 通常,您包含头文件,而不是 cpp 文件。
  • 您不应包含 cpp 文件
  • 你应该包括标题。
  • 你不应该包括你的 cpp phile。
  • @RolandSams 好的,然后尝试假设您的编译器溢出的错误实际上不是错误。

标签: c++ oop reference


【解决方案1】:

您需要将 main 放在文件末尾。 (通常您在单独的 .h 文件中添加类 - 在另一个 .cpp 文件中添加实现 - 在使用该类之前包含您)。 定义,成员作为参考:

class InclObj
{

      public:
            InclObj( PgmClass& );
            void eraseOne( int );

            PgmClass& m_hereitis;
};

InclObj::InclObj( PgmClass& thesource ) :  m_hereitis (thesource)
{

}

这样做你承担了一些责任。例如,在删除原始对象后不要使用eraseOne()。不要尝试添加 InclObj::use_now_this_other_object(PgmClass&amp; other_source) 之类的函数。但我假设您知道...

【讨论】:

  • 啊,这看起来很有希望。我明天会确认它可以工作(我已经编程了超过 12 个小时。非常感谢先生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 2019-05-18
  • 1970-01-01
相关资源
最近更新 更多