Как устранить ошибки компоновщика в моей программе? - PullRequest
0 голосов
/ 31 августа 2011

Хорошо, я пишу этот код для своего класса и получаю ошибки компоновщика LNK2019 и LNK1120 с использованием Visual Studio.Я не совсем уверен, почему он делает то, что делает, но я отвлекся.

Заголовочный файл:

        #ifndef PointClass   
        #define PointClass 
        #include <iostream>

namespace PointClass
    {          
     class point
      {
        public:
        // CONSTRUCTOR
        point(double initial_x = 0.0, double initial_y = 0.0);
        // MODIFICATION MEMBER FUNCTIONS
        void shift(double x_amount, double y_amount);
        void rotate90( );
        // CONSTANT MEMBER FUNCTIONS
        double get_x( ) const { return x; } 
        double get_y( ) const { return y; }
        // FRIEND FUNCTION
        friend std::istream& operator >>(std::istream& ins, point& target);
        double x, y; // x and y coordinates of this point
};

// NONMEMBER FUNCTIONS for the point class 
double distance(const point& p1, const point& p2);
point middle(const point& p1, const point& p2);
point operator +(const point& p1, const point& p2);
bool operator ==(const point& p1, const point& p2);
bool operator !=(const point& p1, const point& p2);
std::ostream& operator <<(std::ostream & outs, const point& source);
        }

        #endif 

И файл CPP:

        #include <iostream>
        #include <math.h>
        #include "point.h"
        using namespace std;

        namespace PointClass
        {
           point::point(double initial_x, double initial_y)
 {
    x = initial_x;   // Constructor sets point to a given position
    y = initial_y;
 }

void point::shift(double x_amount, double y_amount)
 {
    x += x_amount;
    y += y_amount;   
 }

void point::rotate90( )
 {
    double new_x;
    double new_y;
    new_x = y;  // For a 90 degree clockwise rotation the new y is -1
    new_y = -x; // times original x, and the new x is the original y
    x = new_x;
    y = new_y;   
  }

bool operator ==(const point& p1, const point& p2)
 {
    return
        (p1.get_x( ) == p2.get_x( )) 
        &&
        (p1.get_y( ) == p2.get_y( ));
 }

bool operator !=(const point& p1, const point& p2)
  {
    return !(p1 == p2);
  }

point operator +(const point& p1, const point& p2)
  {
    double x_sum, y_sum;

    // Compute the x and y of the sum:
    x_sum = (p1.get_x( ) + p2.get_x( ));
    y_sum = (p1.get_y( ) + p2.get_y( ));
    point sum(x_sum, y_sum);
    return sum;
  }

ostream& operator <<(ostream& outs, const point& source)
 {
    outs << source.get_x( ) <<  " "  << source.get_y( );
    return outs;
 }

istream& operator >>(istream& ins, point& target)
{
    ins >> target.x >> target.y;
    return ins;
 }

int rotations_needed(point p)
  {
    int answer;

    answer = 0;
    while ((p.get_x( ) < 0) || (p.get_y( ) < 0))
        {
          p.rotate90( );
          ++answer;
        }
    return answer;
  }

void rotate_to_upper_right(point& p)
  {
    while ((p.get_x( ) < 0) || (p.get_y( ) < 0))
      p.rotate90( );
  }

double distance(const point& p1, const point& p2)
{
    double a, b, c_squared;

    // Calculate differences in x and y coordinates
    a = p1.get_x( ) - p2.get_x( ); // Difference in x coordinates
    b = p1.get_y( ) - p2.get_y( ); // Difference in y coordinates

    // Pythagorean Theorem to calculate square of distance between points
    c_squared = a*a + b*b;

    return sqrt(c_squared); // sqrt calculates square root
  }

         point middle(const point& p1, const point& p2)
{
    double x_midpoint, y_midpoint;

    // Compute the x and y midpoints
    x_midpoint = (p1.get_x( ) + p2.get_x( )) / 2;
    y_midpoint = (p1.get_y( ) + p2.get_y( )) / 2;

    // Construct a new point and return it
    point midpoint(x_midpoint, y_midpoint);
    return midpoint;
         }
        }

Что я могу сделать, чтобы это исправить?

Ответы [ 2 ]

7 голосов
/ 31 августа 2011

Кажется, у вас есть пространство имен PointClass, а заголовки охраняются с помощью PointClassПопробуйте изменить это для начала.

#ifndef PointClass // Rename this, it might be clashing with your namespace. 
#define PointClass
namespace PointClass
3 голосов
/ 31 августа 2011

Прочитайте сообщение об ошибке:

Linker Error 2019: unresolved external symbol 'symbol' referenced in function 'function'

Он дает вам имя глобальной переменной или (что более вероятно) функции, которая вызывается без определения, т.е. вы не написали тело функции для нее или не добавили источник с его определением в ваш проект.

Ошибка LNK1120 является следствием первой ошибки.

Без полного сообщения об ошибке трудно сказать. Как отметил @Darcy, вы должны изменить имена в #ifdef и #define, начиная с

#define PointClass

говорит препроцессору заменять это имя на ничем в следующем исходном коде. В результате получается безымянное локальное пространство имен. Все имена, определенные в этом локальном пространстве имен, доступны только внутри этого модуля компиляции (файл cpp).

Выберите уникальное имя для «include guard», которое не должно встречаться где-либо еще в программе. Возможный шаблон может имитировать имя файла заголовка:

#define POINT_H
...