【问题标题】:Sorted List, implementation file排序列表,实现文件
【发布时间】:2015-11-05 07:01:31
【问题描述】:

所以我正在解决一个问题,这是给定的信息,但无论出于何种原因,它都无法编译。我完全从教科书中复制,但在实现文件中出现错误,例如 const(非成员函数上不允许使用类型限定符)和 value(成员不可访问)。我猜这只是一个简单的错字或顶部包含的内容,但我无法弄清楚。

 //  SPECIFICATION FILE  ( itemtype.h )

const  int  MAX_ITEM = 5 ; 
enum  RelationType { LESS, EQUAL, GREATER } ; 
class  ItemType   // declares class data type
{       
   public :     //  3 public member functions
     RelationType    ComparedTo ( ItemType ) const;
     void Print() const;
     void Initialize(int number);
   private:
      int value;
};
//  IMPLEMENTATION FILE  ( itemtype.cpp )
//  Implementation depends on the  data type of value. 
  #include  “itemtype.h” 
  #include  <iostream> 
  using namespace std; 

 RelationType ComparedTo ( ItemType  otherItem )  const 
 {      
   if  ( value  <  otherItem.value )   
        return  LESS ;  
   else  if ( value  > otherItem.value )   
        return  GREATER ;  
   else  
        return  EQUAL ; 
 }  
 void Print ( ) const  
 {  cout  <<  value  <<  endl ;
 }
 void Initialize ( int  number ) 
 { 
   value  =  number  ;               
 }

【问题讨论】:

  • 你需要告诉方法实现它们属于一个类。例如“RelationType ItemType::ComparedTo (ItemType otherItem) const”而不是“RelationType CompareTo (ItemType otherItem) const”

标签: c++ compiler-errors sortedlist


【解决方案1】:

有两种可能:要么你的书有问题,要么你没有完全复制代码

在类定义之外定义成员函数时,需要告诉编译器它们属于哪个类:

RelationType ItemType::ComparedTo(ItemType otherItem)  const 
{
     // ...
}

// ...

void ItemType::Print() const
{
  // ...
}

等等。

(从 C++ 的角度来看,类、头文件和实现之间没有任何关系。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 2016-08-31
    • 2016-06-23
    • 2016-09-18
    • 2019-09-30
    相关资源
    最近更新 更多