2015-04-01 4 views
0

Я полный новичок с C++. Я пытаюсь отладить мой код, потому что я уверен, что есть некоторые ошибки указателя и такие, что я все еще пытаюсь понять, но я не могу его скомпилировать. Код исходит из java-программы, которую я написал, которая является только классом песен с некоторыми методами сравнения, и я переписал ее на C++, чтобы попробовать и изучить различия между языками, сам код не показывает ошибок, но он просто не может компиляция без этой ошибки. Я попытался найти решения этой ошибки, но ничего не нашел, так вот мой код для проекта консоли win32. Спасибо вам за помощь.Ошибка C++ LNK2019: неразрешенный внешний символ _main, указанный в функции _tmainCRTStartup

 // ConsoleApplication4.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include <string> 
#include <iostream> 

using namespace std; 

class Song { 
private: 
    string Artist; 
    string Title; 
    string Lyrics; 
public: 
    static int Sortcount; 
    static int Searchcount; 

    Song(string A_Artist, string T_Title, string L_Lyrics) { 

     Artist = A_Artist; 
     Title = T_Title; 
     Lyrics = L_Lyrics; 
    } 

    //Compares the artist of one song to another. 
    class ArtistComparator { 

    public: 
     int compare(Song *o1, Song *o2) { 
      string Artist1 = (*o1).Artist; 
      string Artist2 = (*o2).Artist; 
      Searchcount++; 

      if (Artist1.compare(Artist2) == 0){ 
       return 0; 
      } 
      Searchcount++; 
      return (*o1).Artist.compare((*o2).Artist); 
     } 

    }; 

    //Compares the title of one song to another. 
    class TitleComparator { 

    public: 

     int compare(Song arg0, Song arg1) { 

      string Title1 = arg0.Title; 
      string Title2 = arg1.Title; 
      return Title1.compare(Title2); 
     } 
    }; 


public: 

    //Testing method to make sure the Song class works and 
    //the compareTo method works. 
    int main(int argc, char** argv){ 
     Song test1 = Song("cat", "bat", "this is not a real song"); 
     Song test2 = Song("cat", "apple", "also not a real song"); 
     int compareResult = test1.compareTo(test2); 
     if (compareResult == -1){ 
      std::cout << "test1 comes first"; 
     } 
     else{ 
      cout << "test2 comes first"; 
      cout << test2.toString(); 
     } 

    }; 

    string getArtist(){ 
     return Artist; 
    }; 

    string getTitle(){ 
     return Title; 
    }; 

    string getLyrics(){ 
     return Lyrics; 
    }; 

    string toString(){ 
     return Artist + ", " + Title + ", " + Lyrics; 
    }; 

    //compareTo method used for sorting songs. 
    //increments Sortcount each time it is called to keep track 
    //of the efficiency of the sort algorithm. 
private: 
    int compareTo(Song other){ 
     Sortcount++; 
     int art = Artist.compare(other.Artist); 
     if (art == 0){ 

      return Title.compare(other.Title); 
     } 
     else 
      return art; 
    } 
}; 
+6

В отличие от Java, функция 'main' в C++ (и C) не может быть функцией-членом, она должна быть автономной функцией. –

+0

Просто поместите свой основной() вне определения класса. и вы это сделали. –

ответ

0
#include "stdafx.h" 
#include <string> 
#include <iostream> 

using namespace std; 

class Song { 
private: 
    string Artist; 
    string Title; 
    string Lyrics; 
public: 
    int Sortcount; 
    static int Searchcount; 

    Song(string A_Artist, string T_Title, string L_Lyrics) { 

     Artist = A_Artist; 
     Title = T_Title; 
     Lyrics = L_Lyrics; 
    } 

    //Compares the artist of one song to another. 
    class ArtistComparator { 

    public: 
     int compare(Song *o1, Song *o2) { 
      string Artist1 = (*o1).Artist; 
      string Artist2 = (*o2).Artist; 
      Searchcount++; 

      if (Artist1.compare(Artist2) == 0){ 
       return 0; 
      } 
      Searchcount++; 
      return (*o1).Artist.compare((*o2).Artist); 
     } 

    }; 

    //Compares the title of one song to another. 
    class TitleComparator { 

    public: 

     int compare(Song arg0, Song arg1) { 

      string Title1 = arg0.Title; 
      string Title2 = arg1.Title; 
      return Title1.compare(Title2); 
     } 
    }; 


public: 

    //Testing method to make sure the Song class works and 
    //the compareTo method works. 


    string getArtist(){ 
     return Artist; 
    }; 

    string getTitle(){ 
     return Title; 
    }; 

    string getLyrics(){ 
     return Lyrics; 
    }; 

    string toString(){ 
     return Artist + ", " + Title + ", " + Lyrics; 
    }; 

    //compareTo method used for sorting songs. 
    //increments Sortcount each time it is called to keep track 
    //of the efficiency of the sort algorithm. 
    int compareTo(Song other){ 
     Sortcount++; 
     int art = Artist.compare(other.Artist); 
     if (art == 0){ 

      return Title.compare(other.Title); 
     } 
     else 
      return art; 
    } 
}; 

int main(int argc, char** argv){ 
    Song test1 = Song("cat", "bat", "this is not a real song"); 
    Song test2 = Song("cat", "apple", "also not a real song"); 
    int compareResult = test1.compareTo(test2); 
    if (compareResult == -1){ 
     std::cout << "test1 comes first"; 
    } 
    else{ 
     cout << "test2 comes first"; 
     cout << test2.toString(); 
    } 
    getchar(); 
    return 0; 
} 

изменения сделали:

  1. Переехал main() вне класса
  2. Сделано compareTo() функции public, как это в настоящее время непосредственно называют
  3. Удалены static из int Sortcount, так как я не мог обновить переменная без этого.
+0

* ... поскольку только статические функции могут вносить изменения в статические переменные * это неверно. Причина, по которой он терпит неудачу, когда «SortCount» является статическим, заключается в том, что обе статические переменные объявлены, но не определены. ** декларация ** статической переменной-члена является 'static int SortCount;' внутри определения класса. ** определение ** статической переменной-члена - это 'int Song :: SortCount = 0;', отображающееся в одном исходном файле вне определения класса. Добавление только декларации и забывание определения приводит к ошибке связывания. Это не происходит для другого статического члена, потому что он не используется. – Ionut

+0

Спасибо. Я обновил комментарий :) –

+0

Я видел, но правильным решением является добавление определений для этих статических переменных, а не удаление классификатора 'static'. Удаление «static» изменяет поведение кода. – Ionut

 Смежные вопросы

  • Нет связанных вопросов^_^