2012-02-20 3 views
1

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

-ошибка: по сравнению с предыдущей декларации `RobotDeadReckoner :: RobotDeadReckoner() бросок() '

-Несколько маркеры на этой линии - ошибка: декларации RobotDeadReckoner::RobotDeadReckoner()' throws different exceptions - error: definition of implicitly-declared RobotDeadReckoner :: RobotDeadReckoner()'

-ошибка: НЕТ RobotDeadReckoner::~RobotDeadReckoner()' member function declared in class RobotDeadReckoner»

код выглядит следующим образом:

#include <cmath> 
#include "WPILib.h" 


class RobotDeadReckoner 
{//<---------------------Error 
public: 
    float getX(); 
    float getY(); 
    float getHeading(); 
private: 
    Encoder *encoder1;//Encoder1 (Left Transmision while looking from the back) 
    Encoder *encoder2;//Encoder2 (Right Transmision while looking from the back) 
    int wheelRadius;//Wheel Radius (Center Wheel) 
    float axleWidthCenterToCenter; 
    int encoderTicksPerRotation; 
    int transmitionSprocketTeeth; 
    int wheelSprocketTeeth; 
    int ticksPerRotation; //ticks per rotation of wheel 
    float encoderTicks1; 
    float encoderTicks2; 
    float pi; 
}; 

RobotDeadReckoner::RobotDeadReckoner() 
{//<---------------------Error 
    wheelRadius = 4;//Wheel Radius (Center Wheel) 
    axleWidthCenterToCenter = 30+(7/8); 
    encoderTicksPerRotation = 360; 
    transmitionSprocketTeeth = 12; 
    wheelSprocketTeeth = 26; 
    ticksPerRotation = (wheelSprocketTeeth/transmitionSprocketTeeth)*encoderTicksPerRotation; //ticks per rotation of wheel 

    encoderTicks1 = encoder1->Get(); 
    encoderTicks2 = encoder2->Get(); 

    pi = atan(1)*4; 
} 

float RobotDeadReckoner::getX() 
{ 
    float x = wheelRadius*cos(getHeading())*(encoderTicks1+encoderTicks2)*(pi/ticksPerRotation); 
    return x; 
} 

float RobotDeadReckoner::getY() 
{ 
    float y = wheelRadius*sin(getHeading())*(encoderTicks1+encoderTicks2)*(pi/ticksPerRotation); 
    return y; 
} 

float RobotDeadReckoner::getHeading() 
{ 
    float heading = (2*pi)*(wheelRadius/axleWidthCenterToCenter)*(encoderTicks1-encoderTicks2); 
    return heading; 
} 

RobotDeadReckoner::~RobotDeadReckoner() 
{ //<---------------------Error 

} 

Я уверен, что это нечто глупое, я не знаю о C++, но любая помощь будет оценена!

+1

Обратите внимание, что соглашение для getX() и getY() предполагает, что у вас есть переменная с именем X и другая с именем Y. У вас нет ни одного - заставить ваши геттеры описывать, что они получают. – KevinDTimm

ответ

1

definition of implicitly-declared RobotDeadReckoner::RobotDeadReckoner()

Это самая большая подсказка. У вас нет объявлено конструктор для RobotDeadReckoner(), у вас есть только это. Если вы не предоставляете конструктор по умолчанию, компилятор предоставит вам один, а значит «неявно объявленный». См. What is The Rule of Three?.

no RobotDeadReckoner::~RobotDeadReckoner()' member function declared in classRobotDeadReckoner'

То же самое для деструктора.

Добавьте следующее (public: части) ваш класс декларации:

RobotDeadReckoner(); 
virtual ~RobotDeadReckoner(); 
+0

Спасибо! Я не понимал, что это значит, но это довольно очевидно после того, как я это увидел ... – Jacob9706

+0

@ Jacob9706: Приятно помочь. Добро пожаловать в StackOverflow :) – Johnsyweb

0

Вы должны объявить деструктор (и конструктор) в определении класса первой.

class RobotDeadReckoner 
{//<---------------------Error 
public: 
    RobotDeadReckoner(); 
    ~RobotDeadReckoner(); // <--- HERE 
    float getX(); 
    float getY(); 
    float getHeading(); 
private: 
    Encoder *encoder1;//Encoder1 (Left Transmision while looking from the back) 
    Encoder *encoder2;//Encoder2 (Right Transmision while looking from the back) 
    int wheelRadius;//Wheel Radius (Center Wheel) 
    float axleWidthCenterToCenter; 
    int encoderTicksPerRotation; 
    int transmitionSprocketTeeth; 
    int wheelSprocketTeeth; 
    int ticksPerRotation; //ticks per rotation of wheel 
    float encoderTicks1; 
    float encoderTicks2; 
    float pi; 
}; 
1

Первая часть вашего сообщения - это определение класса, оно должно содержать декларации всех членов. Конструкторы и деструкторы. Они не присутствуют в вашем определении класса.

class Robot{ declarations. }; // end of class definition 

В приведенном ниже классе нет соответствующей декларации.

RobotDeadReckoner::RobotDeadReckoner() 

Кроме того, вы должны поставить свой класс в .h файле и

RobotDeadReckoner::RobotDeadReckoner() 

в файле .cpp.

Так что ваш класс должен выглядеть следующим образом:

class RobotDeadReckoner{ 
    RobotDeadReckoner(); 
    ~RobotDeadReckoner(); 
etc... 
0

Вы заявили ни RobotDeadReckoner конструктор, ни деструктор, так что вы не можете определить их дальше вниз с RobotDeadReckoner::RobotDeadReckoner() и RobotDeadReckoner::~RobotDeadReckoner().

Внутри объявления класса, добавить

RobotDeadReckoner(); 
~RobotDeadReckoner(); 

, а затем определения дальше вниз будет компилировать.

0

Вы можете только обеспечить реализацию для пользовательских конструкторов и деструкторов:

class RobotDeadReckoner 
{ 
public: 
    //declare constructor and destructor 
    RobotDeadReckoner(); 
    ~RobotDeadReckoner(); 
public: 
    float getX(); 
    float getY(); 
    float getHeading(); 
private: 
    Encoder *encoder1;//Encoder1 (Left Transmision while looking from the back) 
    Encoder *encoder2;//Encoder2 (Right Transmision while looking from the back) 
    int wheelRadius;//Wheel Radius (Center Wheel) 
    float axleWidthCenterToCenter; 
    int encoderTicksPerRotation; 
    int transmitionSprocketTeeth; 
    int wheelSprocketTeeth; 
    int ticksPerRotation; //ticks per rotation of wheel 
    float encoderTicks1; 
    float encoderTicks2; 
    float pi; 
}; 

Если вы не объявить конструктор или деструктор для класса, компилятор автоматически генерирует по умолчанию один для вас, которые вы не можете реализовать.

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