2015-11-30 4 views
-2

Я пытаюсь решить этот вопрос назначения с 3 дней и, честно говоря, у меня закончились решения. Я создал объявление класса Plant, тип атрибута, и я перегрузил операторы == &! =, Но я постоянно получаю сообщение об ошибке, не могу преобразовать аргумент 1 из const char [6] в Plant? Я не уверен, что мне не хватает?Невозможно преобразовать аргумент 1 из 'const char [6]' в Object

#include <iostream> 
#include <stdio.h> 
#include <string.h> 
using namespace std; 


class Plant { 
private: 
char* type[10]; //Declare the type attribute of type Char [10] 

    Plant(char* type1[10]); //Declare the const type1 of Object Plant 

    bool operator==(const Plant &b) const 
    { 
     return ((type ==b.type)); 
    } 
    bool operator!=(const Plant &b) const 
    { 
    return ((b.type!=type)); 
    } 

    //overload the print function 
    void print() 
    { cout << type; 
    } 

     };//end class Plant 

     class Fruit: public Plant { 
     public: 
     char* taste [10]; 

     public: 
     bool operator==(const Fruit& rhs) const 
     { 
     //return (taste == rhs.taste && type == rhs.type); 
     return (taste == rhs.taste); 
     } 

     bool operator!=(const Fruit& rhs) const 
     { return (taste != rhs.taste); 
     //return (taste != rhs.taste && type != rhs.type); 
     } 

     void print() 
     {printf("Hi Fruit"); 
     cout << taste; 
     } // print to know if I reached this part 

     };//end class Fruit 


      int main() { 
      Plant a((char*)"Maple"); 
      a.print(); 
      Plant b("Maple"); 

      if (a == b) 
      printf("a and b are equal\n"); 
      else 
      printf("a and b are not equal\n"); 
      if (a != b) 
      printf("a and b are not equal\n"); 
      else 
      printf("a and b are equal\n"); 

      Fruit c("Apple","sweet"); 
      c.print(); 
      Fruit d("Apple","sweet"); 

      if (c == d) 
      printf("c and d are equal\n"); 
      else 
      printf("c and d are not equal\n"); 
      if (c != d) 
      printf("c and d are not equal\n"); 
      else 
      printf("c and d are equal\n"); 

      if (a == c) 
      printf("a and c are equal\n"); 
      else 
      printf("a and c are not equal\n"); 
      if (a != c) 
      printf("a and c are not equal\n"); 
      else 
      printf("a and c are equal\n"); 

      if (c == a) 
      std::cout <<"c and a are equal\n"<< std::endl; 
      else 
      std::cout <<"c and a are not equal\n"<< std::endl; 
      if (a != c) 
      std::cout <<"c and a are not equal\n"<< std::endl; 
      else 
      std::cout <<"c and a are equal\n"<< std::endl; 

      return 0; 
      } 

Я новичок в C++ только начал изучать, и я прочитал следующие ресурсы:

  1. http://faculty.cs.niu.edu/~mcmahon/CS241/Notes/relational.html
  2. http://www.cplusplus.com/doc/tutorial/basic_io/ и многие другие сайты, но я не разрешается размещать более 2.

Любой совет или помощь будут высоко оценены ..

Спасибо!

+1

Рекомендации: не используйте 'char *', не используйте 'printf'. – erip

+0

@erip спасибо за прохождение, я попытаюсь отредактировать свой код и, надеюсь, исправить это, но только примечание стороны, мы должны добавить код к классу Plant and Class Fruit. Основной класс не следует трогать его. – Lucyia

+0

Все функции-члены 'Plant' являются частными, включая конструктор. Таким образом, класс 'Plant' не может быть создан, кроме как с помощью функции-члена. Основная функция - не такой член. –

ответ

1

Ошибки здесь объясняются недоразумениями о строках в стиле C и, вероятно, исчезнут, если вы использовали std::string.

Например:

bool operator==(const Plant &b) const 
{ 
    return ((type ==b.type)); 
} 

Это не сравнить две строки. Он сравнивает указатели под названием type. Вы должны использовать функцию strcmp.

char* type[10]; Это не создает строку из 9 или 10 символов, которую я предполагаю, это то, что вы хотели. Это массив из 10 char указателей. Я думаю, вы хотели char type[10]. Это зарезервирует место для строки символов плюс нулевой ограничитель. Если вы попытаетесь сохранить больше, чем это, ваша программа будет демонстрировать неопределенное поведение, и вы даже не можете получить сообщение об ошибке.

(char*)"Maple" Это отливка в стиле C. Не используйте их. Используйте static_cast, и если код не компилируется, вы, вероятно, делаете что-то неправильно. Никогда не добавляйте бросок «просто для его компиляции».

Опять же, я настоятельно рекомендую вам использовать std::string, который работает намного больше, чем типы строк других языков и имеет большую безопасность.

+0

Спасибо Нилу за то, что нашли время, чтобы проиллюстрировать это мне. Я действительно смущен, потому что в Интернете есть много ресурсов, а некоторые просто дают информацию о конфликте. Вот почему я размещаю свой вопрос здесь. – Lucyia

1

Я очистил ваш код, чтобы использовать более идиоматические конструкции C++, такие как std::string.

#include <iostream> 
#include <string> 

class Plant { 
    public: 
    Plant(std::string name) : type_(name) {} 
    bool operator==(const Plant &that) const { 
     return type_ == that.type_; 
    } 
    bool operator!=(const Plant &that) const { 
     return !operator==(that); 
    } 
    void print() { std::cout << type_ << std::endl; } 
protected: 
    std::string type_; 
}; 

class Fruit: public Plant { 
    public: 
    Fruit(std::string name, std::string taste) : Plant(name), taste_(taste) {} 
    bool operator==(const Fruit& that) const { 
     return ((taste_ == that.taste_) && (Plant::operator==(that))); 
    } 

    bool operator!=(const Fruit& that) const { 
     return !operator==(that); 
    } 

    void print() { Plant::print(); std::cout << taste_ << std::endl; } 
    private: 
    std::string taste_; 
}; 


int main() { 
    Plant a("Maple"); 
    a.print(); 
    Plant b("Maple"); 

    if (a == b) { 
    std::cout << "a and b are equal" << std::endl; 
    } else { 
    std::cout << "a and b are not equal" << std::endl; 
    } 

    Fruit c("Apple","sweet"); 
    c.print(); 
    Fruit d("Apple","sweet"); 

    if (c == d) { 
    std::cout << "c and d are equal" << std::endl; 
    } else { 
    std::cout << "c and d are not equal" << std::endl; 
    } 

    if (a == c) { 
    std::cout << "a and c are equal" << std::endl; 
    } else { 
    std::cout << "a and c are not equal" << std::endl; 
    } 

    return 0; 
} 

Когда я запускаю это, я получаю этот выход:

23:24 $ ./a.out 
Maple 
a and b are equal 
Apple 
sweet 
c and d are equal 
a and c are not equal 

Вот ideone.

+0

Почему «Fruit» не сравнивает «тип»? Его операторы должны вызывать родительские. –

+0

Код OP также не сравнивает строки: p –

+0

Вы ничего не делаете с возвращаемым значением родительских операторов. –

1

Добро пожаловать в мир C++. Я думаю, вы хотите избавиться от всех этих массивов символов и указателей символов теперь, когда вы вошли в область C++. std :: string - очень мощная инкапсуляция всех основных операций с строками, которые вы можете выполнить. Пожалуйста, обратитесь к http://www.cplusplus.com/reference/string/string/ за полным определением API класса std :: string.Основываясь на моем понимании того, чего вы хотите достичь, я изменил вашу программу на использование std :: string. Эта программа компилируется и работает нормально. Дайте мне знать, если у вас возникли трудности с пониманием программы, и я могу пронести вас через нее. Также обратите внимание на использование параметризованных конструкторов и списков инициализации, сведения о которых вы можете узнать на одном и том же сайте, который я поделился с вами. Я буду более чем счастлив помочь вам в любом аспекте написания программы на C++.

#include <iostream> 
#include <stdio.h> 
#include <string.h> 
using namespace std; 


class Plant { 
private: 
std::string type; //Declare the type attribute of type Char [10] 

public: 
    Plant(std::string type1) : type(type1) {}//Declare the const type1 of Object Plant 

    bool operator==(const Plant &b) const 
    { 

     return (type == b.type); 
    } 
    bool operator!=(const Plant &b) const 
    { 
    return (b.type != type); 
    } 

    //overload the print function 
    void print() 
    { 
     cout << type; 
    } 

     };//end class Plant 

     class Fruit: public Plant { 
     public: 
     std::string taste; 

     public: 
     Fruit(std::string fruit, std::string t) : Plant(fruit), taste(t) {} 
     bool operator==(const Fruit& rhs) const 
     { 
     //return (taste == rhs.taste && type == rhs.type); 
     return (taste == rhs.taste); 
     } 

     bool operator!=(const Fruit& rhs) const 
     { return (taste != rhs.taste); 
     //return (taste != rhs.taste && type != rhs.type); 
     } 
     void print() 
     {printf("Hi Fruit"); 
     cout << taste; 
     } // print to know if I reached this part 

     };//end class Fruit 


      int main() { 
      Plant a("Maple"); 
      a.print(); 
      Plant b("Maple"); 

      if (a == b) 
      printf("a and b are equal\n"); 
      else 
      printf("a and b are not equal\n"); 
      if (a != b) 
      printf("a and b are not equal\n"); 
      else 
      printf("a and b are equal\n"); 

      Fruit c("Apple", "sweet"); 
      c.print(); 
      Fruit d("Apple", "sweet"); 

      if (c == d) 
      printf("c and d are equal\n"); 
      else 
      printf("c and d are not equal\n"); 
      if (c != d) 
      printf("c and d are not equal\n"); 
      else 
      printf("c and d are equal\n"); 

      if (a == c) 
      printf("a and c are equal\n"); 
      else 
      printf("a and c are not equal\n"); 
      if (a != c) 
      printf("a and c are not equal\n"); 
      else 
      printf("a and c are equal\n"); 


      return 0; 
      } 
+0

Спасибо, или ваш комментарий и предложение, чтобы помочь, я действительно ценю это. – Lucyia