Program should run... fatal error LNK1120 and error LNK2019 - c++

We were given a header and cpp file for our next project from which we need to derive a class. These two files should work properly "out of the box" but for some reason I'm getting these errors and clicking on the errors doesn't take me anywhere. I'm guessing it's a version problem since most of the books programs are of extension .cxx and we're working with .cpp, but I'm pretty new to programming so I don't know for sure. Also, most of the books other programs worked just fine in VS 2012. I'm using Visual Studio 2012 on Windows 7 64bit if that helps.
Errors:
1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
1>Projects\Project 5\Debug\Project 5.exe : fatal error LNK1120: 1 unresolved externals
Here is the code for the header and cpp of our base class and thanks for the help guys:
Header:
#ifndef MAIN_SAVITCH_GAME
#define MAIN_SAVITCH_GAME
#include <queue> // Provides queue<string>
#include <string> // Provides string
namespace main_savitch_14
{
class game
{
public:
// ENUM TYPE
enum who { HUMAN, NEUTRAL, COMPUTER }; // Possible game outcomes
// CONSTRUCTOR and DESTRUCTOR
game( ) { move_number = 0; }
virtual ~game( ) { }
// PUBLIC MEMBER FUNCTIONS
// The play function should not be overridden. It plays one game,
// with the human player moving first and the computer second.
// The computer uses an alpha-beta look ahead algorithm to select its
// moves. The return value is the winner of the game (or NEUTRAL for
// a tie).
who play( );
protected:
// *******************************************************************
// OPTIONAL VIRTUAL FUNCTIONS (overriding these is optional)
// *******************************************************************
virtual void display_message(const std::string& message) const;
virtual std::string get_user_move( ) const;
virtual who last_mover( ) const
{ return (move_number % 2 == 1 ? HUMAN : COMPUTER); }
virtual int moves_completed( ) const { return move_number; }
virtual who next_mover( ) const
{ return (move_number % 2 == 0 ? HUMAN : COMPUTER); }
virtual who opposite(who player) const
{ return (player == HUMAN) ? COMPUTER : HUMAN; }
virtual who winning( ) const;
// *******************************************************************
// VIRTUAL FUNCTIONS THAT MUST BE OVERRIDDEND:
// The overriding function should call the original when it finishes.
// *******************************************************************
// Have the next player make a specified move:
virtual void make_move(const std::string& move) { ++move_number; }
// Restart the game from the beginning:
virtual void restart( ) { move_number = 0; }
// *******************************************************************
// PURE VIRTUAL FUNCTIONS
// *******************************************************************
// (these must be provided for each derived class)
// Return a pointer to a copy of myself:
virtual game* clone( ) const = 0;
// Compute all the moves that the next player can make:
virtual void compute_moves(std::queue<std::string>& moves) const = 0;
// Display the status of the current game:
virtual void display_status( ) const = 0;
// Evaluate a board position:
// NOTE: positive values are good for the computer.
virtual int evaluate( ) const = 0;
// Return true if the current game is finished:
virtual bool is_game_over( ) const = 0;
// Return true if the given move is legal for the next player:
virtual bool is_legal(const std::string& move) const = 0;
private:
// MEMBER VARIABLES
int move_number; // Number of moves made so far
// STATIC MEMBER CONSTANT
static const int SEARCH_LEVELS = 4; // Levels for look-ahead evaluation
// PRIVATE FUNCTIONS (these are the same for every game)
int eval_with_lookahead(int look_ahead, int beat_this);
void make_computer_move( );
void make_human_move( );
};
}
#endif
CPP:
#include <cassert> // Provides assert
#include <climits> // Provides INT_MAX and INT_MIN
#include <iostream> // Provides cin, cout
#include <queue> // Provides queue<string>
#include <string> // Provides string
#include "game.h" // Provides definition of game class
using namespace std;
namespace main_savitch_14
{
//*************************************************************************
// STATIC MEMBER CONSTANTS
const int game::SEARCH_LEVELS;
//*************************************************************************
// PUBLIC MEMBER FUNCTIONS
game::who game::play( )
// The play function should not be overridden. It plays one round of the
// game, with the human player moving first and the computer second.
// The return value is the winner of the game (or NEUTRAL for a tie).
{
restart( );
while (!is_game_over( ))
{
display_status( );
if (last_mover( ) == COMPUTER)
make_human_move( );
else
make_computer_move( );
}
display_status( );
return winning( );
}
//*************************************************************************
// OPTIONAL VIRTUAL FUNCTIONS (overriding these functions is optional)
void game::display_message(const string& message) const
{
cout << message;
}
string game::get_user_move( ) const
{
string answer;
display_message("Your move, please: ");
getline(cin, answer);
return answer;
}
game::who game::winning( ) const
{
int value = evaluate( ); // Evaluate based on move that was just made.
if (value > 0)
return COMPUTER;
else if (value < 0)
return HUMAN;
else
return NEUTRAL;
}
//*************************************************************************
// PRIVATE FUNCTIONS (these are the same for every game)
int game::eval_with_lookahead(int look_ahead, int beat_this)
// Evaluate a board position with lookahead.
// --int look_aheads: How deep the lookahead should go to evaluate the move.
// --int beat_this: Value of another move that we’re considering. If the
// current board position can't beat this, then cut it short.
// The return value is large if the position is good for the player who just
// moved.
{
queue<string> moves; // All possible opponent moves
int value; // Value of a board position after opponent moves
int best_value; // Evaluation of best opponent move
game* future; // Pointer to a future version of this game
// Base case:
if (look_ahead == 0 || is_game_over( ))
{
if (last_mover( ) == COMPUTER)
return evaluate( );
else
return -evaluate( );
}
// Recursive case:
// The level is above 0, so try all possible opponent moves. Keep the
// value of the best of these moves from the opponent's perspective.
compute_moves(moves);
assert(!moves.empty( ));
best_value = INT_MIN;
while (!moves.empty( ))
{
future = clone( );
future->make_move(moves.front( ));
value = future->eval_with_lookahead(look_ahead-1, best_value);
delete future;
if (value > best_value)
{
if (-value <= beat_this)
return INT_MIN + 1; // Alpha-beta pruning
best_value = value;
}
moves.pop( );
}
// The value was calculated from the opponent's perspective.
// The answer we return should be from player's perspective, so multiply times -1:
return -best_value;
}
void game::make_computer_move( )
{
queue<string> moves;
int value;
int best_value;
string best_move;
game* future;
// Compute all legal moves that the computer could make.
compute_moves(moves);
assert(!moves.empty( ));
// Evaluate each possible legal move, saving the index of the best
// in best_index and saving its value in best_value.
best_value = INT_MIN;
while (!moves.empty( ))
{
future = clone( );
future->make_move(moves.front( ));
value = future->eval_with_lookahead(SEARCH_LEVELS, best_value);
delete future;
if (value >= best_value)
{
best_value = value;
best_move = moves.front( );
}
moves.pop( );
}
// Make the best move.
make_move(best_move);
}
void game::make_human_move( )
{
string move;
move = get_user_move( );
while (!is_legal(move))
{
display_message("Illegal move.\n");
move = get_user_move( );
}
make_move(move);
}
}

You don't have int main() function. Every program must have this.
http://en.wikipedia.org/wiki/Main_function

They may compile properly out of the box but, without a main function, they won't link or run.
You need to combine them with your own source code, which I would expect to contain at least a main function which used those classes somehow. As a first step, start with:
int main(void) {
return 0;
}
That won't do anything useful but it should get you over the immediate link errors.

Related

No instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=Enemy *, _Alloc=std::allocator<Enemy *>]" matches the argument list

for (auto enemy : this->enemies)
{
if (enemy->getHP() <= 0)
{
enemies.erase(enemy);
}
}
I have a vector enemies containing multiple of Enemy* elements and i want to erase an enemy if their hp is 0 or below
I write the code above and it gave me this error message:
No instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=Enemy *, _Alloc=std::allocator<Enemy *>]" matches the argument list
argument types are: (Enemy*)
object type is: std::vector<Enemy*,std::allocator<Enemy*>>
I assume that is not the right way to do it, so how?
Im new in stackoverflow and im still learning english so sorry if i made mistakes
EDIT:
It's my almost complete code:
struct enemyType
{
public:
int type;
sf::Vector2f pos;
}
std::vector<std::vector<enemyType>> enemyList = {
{
{ trashMonster, sf::Vector2f(5.f * 16, 18.f * 16) }
}
}
std::vector<Enemy*> enemies;
std::vector<Enemy*>* GetEnemy(int level)
{
for (int i = 0; i < enemyList[level].size(); i++)
{
switch (enemyList[level][i].type)
{
case trashMonster:
n_TrashMonster->setPosition(enemyList[level][i].pos);
enemies.emplace_back(n_TrashMonster);
break;
default:
std::cout << "Error to get an enemy\n";
break;
}
}
return &enemies;
}
//Code in different file
std::vector<Enemy*> enemies;
this->enemies = *GetEnemy(lvl);
for (auto enemy : this->enemies)
{
enemy->update(player->getCollisionBox());
//collision enemies to tilemap
collision::MapCollision(*this->map.getTilesCol(), *enemy);
if (enemy->getHP() <= 0)
{
enemies.erase(enemy);
}
}
Didn't include that because my code is a complete mess so I was afraid people won't get the point of my question and it's my first question here
The std::vector<T>::erase function does not have a erase(T a) overload. And if you want to remove elemennts from a vector you can't iterate over them like that. I suggest a convencional loop.
for (size_t i=0; i<this->enemies.size();++i){
if (this->enemies[i]->getHP()){
std::swap(enemies[i],enemies::back());
delete enemies::back();//Only if you don't free the space elsewere
enemies.pop_back();
}
}
Edit:
This will mess up the order of the vector. If you don't want that you can use erase(enemies.begin()+i) iinstead of swaping it back and removeing it
When using STL containers usually you don't even need an (explicit) for loop. Use std::remove_if like this
#include <vector>
#include <algorithm>
#include <iostream>
class Enemy
{
public:
// not explicit on purpose, so I can initalize vector more quickly (in real code you should have explicit constructors if they have one argument of a different type)
Enemy(int hp) :
m_hp{ hp }
{
};
int getHP() const noexcept
{
return m_hp;
}
int m_hp;
};
int main()
{
// create a test vector with enemies with given hitpoints
std::vector<Enemy> enemies{ 1,2,0,4,5,6,0,7,8 };
// boolean lambda function that determines if an enemy is dead.
auto enemy_is_dead = [](const Enemy& enemy) { return enemy.getHP() <= 0; };
// use remove_if (this will move all the items to be removed to the end
auto remove_from = std::remove_if(enemies.begin(), enemies.end(), enemy_is_dead );
// then shrink the vector
enemies.erase(remove_from, enemies.end());
for (const auto& enemy : enemies)
{
std::cout << enemy.getHP() << " ";
}
return 0;
}

Member function doesn't work when using pointer to class

Scenario: I have two classes, each contains a pointer to the other (when using them, being able to refer to the other is going to be important so I deemed this appropriate). When I try accessing a private variable from one class via using the pointer to the other and a getter function inside that, it works perfectly.
Problem: Using a setter (in this case, addPoints)/manipulating the variables however leads to no result.
I'm new so anything here might be "improper etiquette" and bad practice. Feel free to point them out! But please also try to provide a solution. This is also my first question on SO, so please be gentle!
Related code pieces:
Team.h
#include "Driver.h"
using namespace std;
class Team {
int Points = 0;
vector<Driver*> Drivers;
public:
void addPoints(int gained); //does not work
int getPoints(); //works perfectly
Driver getDriver(int nr);
void setInstance(vector<Driver*> drivers);
};
Team.cpp
#include "Team.h"
#include "Driver.h"
using namespace std;
void Team::addPoints(int gained) {
this->Points = this->Points + gained;
}
int Team::getPoints() {
return this->Points;
}
Driver Team::getDriver(int nr) {
return *Drivers[nr];
}
void Team::setInstance(vector<Driver*> drivers) {
this->Drivers = drivers;
}
Driver.h
using namespace std;
class Team;
class Driver {
int Points = 0;
Team* DriversTeam;
public:
void SetTeam(Team& team);
Team getTeam();
int getPoints(); //works
void addPoints(int gained); //doesn't work
};
Driver.cpp
#include "Driver.h"
#include "Team.h"
using namespace std;
void Driver::SetTeam(::Team& team) {
this->DriversTeam = &team;
}
Team Driver::getTeam() {
return *DriversTeam;
}
int Driver::getPoints() {
return this->Points;
}
void Driver::addPoints(int gained) {
this->Points = this->Points + gained;
}
Initializer.cpp (linking drivers to teams)
void InitializeData(vector<Team>& teams, vector<Driver> &drivers) {
//(...)
//reads each team in from data file to memory
//key part:
vector<Driver*> teamsDrivers;
for (auto& iter : drivers) { //this loop mainly determines which driver to link with which teams
if (iter.getName().compare(values[4]) == 0) { //values is csv line data in a string vector. I guess not the prettiest parsing method here but will be revised
teamsDrivers.push_back(&iter);
}else if(iter.getName().compare(values[5]) == 0) {
teamsDrivers.push_back(&iter);
}
}
tempTeam.setInstance(teamsDrivers);
teams.push_back(tempTeam);
}
(linking driver to team)
//drivers are linked to teams last, as they are declared first (so I cannot link them to the yet nonexisting teams)
void LinkTeam(vector<Driver>& drivers, vector<Team>& teams) {
for (auto& driverIter : drivers) { //iterate through drivers
for (auto& teamIter : teams) { // iterate through teams
bool found = 0;
for (size_t i = 0; i < teamIter.DriverAmount(); i++) {
if (driverIter.getName() == teamIter.getDriver(i).getName()) {
driverIter.SetTeam(teamIter);
found = 1;
break;
}
}
if (found) { //exit iterating if driver is found
break;
}
}
}
}
Example of use in main.cpp
teams[0].addPoints(10);
drivers[3].getTeam().addPoints(15); //driver 3 is linked to team 0
cout << teams[0].getPoints(); //15
cout << drivers[3].getTeam().getPoints(); //15
teams[0].getDriver(1).addPoints(20); //driver 1 of team 0=driver[3]
drivers[3].addPoints(25);
cout << drivers[3].getPoints(); //25
cout << teams[0].getDriver(1).getPoints(); //25
Thanks for the help in advance.
This is quite simple:
Your getTeam() and getDriver() functions are returning copies of the objects, not references, so the addPoints() are performed on temporary copies and not the real ones.
To fix it, simply change the return types to references (add &):
Team& getTeam();
and
Driver& getDriver();

C++ No matching member function for call to 'push_back' error for vector

I have been working with a vector and I receive this error:
No matching member function for call to 'push back'
Can anyone take a look at my code to detect my mistakes?
bubble_jar.h
#include "abstract_bubble.h"
#include "bubbles.h"
#include <vector>
#include "cpputils/graphics/image.h"
#ifndef BUBBLE_JAR_H
#define BUBBLE_JAR_H
class BubbleJar : public graphics::MouseEventListener,
public graphics::AnimationEventListener {
public:
~BubbleJar();
void Initialize(int max_age);
void Start();
void OnMouseEvent(const graphics::MouseEvent& event) override;
void OnAnimationStep() override;
graphics::Image* GetImageForTesting() { return &image_; }
private:
graphics::Image image_;
int max;
std::vector<std::unique_ptr<AbstractBubble>> ab;
};
#endif // BUBBLE_JAR_H
bubble_jar.cc
void BubbleJar::OnMouseEvent(const graphics::MouseEvent& event) {
std::cout << "BubbleJar got a MouseEvent" << std::endl;
// Create a BigBubble on mouse press and a SmallBubble on mouse release
// and add them to the vector.
if (event.GetMouseAction() == graphics::MouseAction::kPressed) {
BigBubble b(event.GetX(), event.GetY(), &image_);
ab.push_back(b);
b.Draw();
}
else if ( event.GetMouseAction() == graphics::MouseAction::kReleased ) {
SmallBubble s(event.GetX(), event.GetY(), &image_);
ab.push_back(s);
s.Draw();
}
image_.Flush();
}
Your std::vector holds std::unique_ptr smart pointers to AbstractBubble-derived objects, but you are trying to push actual derived objects, not smart pointers to derived objects, hence the push_back() error due to a type mismatch.
Try this instead:
void BubbleJar::OnMouseEvent(const graphics::MouseEvent& event) {
std::cout << "BubbleJar got a MouseEvent" << std::endl;
// Create a BigBubble on mouse press and a SmallBubble on mouse release
// and add them to the vector.
if (event.GetMouseAction() == graphics::MouseAction::kPressed) {
auto b = std::make_unique<BigBubble>(event.GetX(), event.GetY(), &image_);
ab.push_back(std::move(b));
b->Draw();
}
else if ( event.GetMouseAction() == graphics::MouseAction::kReleased ) {
auto s = std::make_unique<SmallBubble>(event.GetX(), event.GetY(), &image_);
ab.push_back(std::move(s));
s->Draw();
}
image_.Flush();
}

C++ Struct defined data passing. Simple answer im sure

I am sure this is a very simple fix and I feel dumb asking it but here it goes.
I need help with a struct and passing info from a gather function to a save or set function, and then passing it again to another function for further use.
Basically, it looks like this to start. I'll just add short snips of the code. All can be provided if you would like to see it.
I right now am just looking for the proper way to pass struct defined data from get.... to set.... functions.
struct printype
{
char dots[8][15];
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
};
int getunknown15(); // prototypes
int setunknown15(int);
then we have a simple main.
int main()
{
printype pt;
pt.unknown15=getunknown15();
pt.unknown15=setunknown15(12);
pt.serial11_14=getserial11_14();
pt.serial11_14=setserial11_14("12345678");
pt.year8=getyear8();
pt.year8=setyear8(44);
pt.month7=getmonth7();
pt.month7=setmonth7(11);
pt.day6=getday6();
pt.day6=setday6(12);
pt.hour5=gethour5();
pt.hour5=sethour5(12);
pt.minute2=getminute2();
pt.minute2=setminute2(23);
cout <<"-----------------------------------------------------"<<endl;
cout <<" Let's Get Started"<<endl;
cout <<"-----------------------------------------------------"<<endl;
setup(pt.dots); // sets up the array
dpinfo(pt); // prints out the final array
ftarray(pt);
spar(pt.dots);
darray(pt.dots);
}
and finally the get and set array functions.
int getunknown15()
{
printype tem;
cout <<"-----------------------------------------------------"<<endl;
cout <<" Enter the Unkown Variable (0-127): ";
cin >>tem.unknown15;
cout <<"-----------------------------------------------------"<<endl;
return tem.unknown15;
}
next is
int setunknown15(int tem)
{
printype pp;
if (tem>127||tem<0)
{
cout << "Error" << endl;
return 0;
}
else
{
pp.unknown15 = tem;
return pp.unknown15;
}
}
I hope this isn't too much to read and understand
Anyway, I know this has a really simple answer but my brain just isn't working right now.
Edit: As StilesCrisis stated, Send struct as parameter is quiet stupid in this case. better use a const reference.
Well, I am not sure if I understand your question correctly. You can simply send struct to another function as parameter, or as a pointer.
like:
void SetStruct(const printype& var);
printype GetStruct();
Is it what you are looking for?
Please use the following access to the your fields, (by reference):
struct printype *myPtr = new printype;
myPtr->day6 = 43;
When use pointer instead of a normal variable, you should use -> instead . to access your fields.
I know this is kind of old but I thought I should give it a shot, since you are using C++ and it looks like you are trying to use some OO practices (I think), you don't need to start with a struct, even though OO principles can be applied using them as well though not as elegantly.
you can define your class header file as such.
#ifndef PRINTYPE_H
#define PRINTYPE_H
#include <string>
using namespace std;
class printype
{
private: // we always want to declare our member fields private for safety/managements reasons, no one will be able to access them outside.
char dots[8][15];
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
void init(); // This is the method we use to initialize our starting state.
public: // This is our public methods, how people deal with/get/set our state.
printype(); // This is our default constructor
printype(const printype& print_type); // This our copy constructor
virtual ~printype(); // This is our destructor, its virtual, making safer for inheritance.
// This is our setters/getters
void setUnknown(int unknown);
int getUnknown();
void setYear(int year);
int getYear();
void setMonth(int mont);
int getMonth();
// and well you get the idea, you can add more methods.
};
#endif
and the accompanying class source file with your functions implementation
printype::printype()
{
this->init(); // Initialize all your vatiables, safer to just define a function to this.
}
printype::printype(const printype& orig) // copy constructor
{
this->setUknown(orig.getUnknown());
this->setDay(orig.getDay());
this->setDots(orig.getDots());
// you get the idea ...
}
printype::~printype()
{
// Have anything you need to do before destroying the object.
}
void printype::init()
{
this->setUnknwon(0);
this->setyear(0);
this->setMonth(1);
char dots[8][15] = {'\0'};
this->setDots(dots);
// you get the idea, you want to initialize all your variables since, for the most part they initially hold garbage.
}
void printype::setUnknown(int unknown)
{
if (unknown >= 0 && unknown < 127)
this->unknown15 = unknown;
else
error("Expecting unknown to be between 0 and 127"); // error should probably print the error and/or exit(-1) up to u
}
int printype::setYear(int year)
{
if (year >= 1 && year <= 99)
this->year8 = year;
else
error("Expecting year between 0 and 99"); // you may want to implement an error function!
}
int printype::getYear()
{
return this->year8;
}
void printype::setDots(char dots[8][15])
{
// you may want to do some verifications
memcpy(this->dots, dots, sizeof(dots));
}
void printype::setDots(char **dots) // this is a bit unsafe, use at your own risk.
{
if (dots)
{
unsigned int index = 0;
for (index = 0; index < 8; index++)
if (dots[index])
memcpy(this->dots[index], dots[index], 15);
else
error("dots required pointer ...");
}
else
error("dots required pointer ...");
}
char **getDots() // We will be returning a copy, we don't want the internal state to be affected, from outside, by using reference or pointers.
{
char **dots = new char*[8];
unsigned int index = 0;
for (index = 0; index < 8; index++)
{
dots[index] = new char[15];
memcpy(dots[index], this->dots[index], 15);
}
return dots;
}
// and well you get the idea ...
to use your class
printype *print_type_p = new print_type();
// or
printype pront_type_p();
// use the different public method to update the internal state.
print_type_p->setYear(3);
// or
print_type.setYear(3);
print_type_p->getYear();
// and so on.

Exception Error while making a Clock/Timer class

I am trying to make a Clock with the timeGetTime function and some others. But I keep getting an exception error. I know mayby the quality of the program is not really good, but I was just trying to get it work. It's supposed to be a singleton. I hope you can help me!
// The Clock header file
// The Clock API for meassuring time.
#include<Windows.h>
#include<WinBase.h>
#include<MMSystem.h>
class cTime
{
private:
double m_Ns;
double m_Ms;
double m_S;
public:
// Set Values
void SetN(double N) {m_Ns = N;}
void SetM(double M) {m_Ns = M;}
void SetS(double S) {m_Ns = S;}
// Get Values
double GetN() {return m_Ns;}
double GetM() {return m_Ms;}
double GetS() {return m_S;}
// GetTime functions
//int GetDiffrenceNs();
//int GetDiffrenceMs();
//int GetDiffrenceS();
};
class cClock
{
private:
cTime m_CurrentTime; // CurrentTime object
static cClock* m_pClock; // Pointer to only instance
cTime m_LastTime; // LastTime object
bool m_PerformanceCounter; // Set to true if the performance counter is available
double m_Frequency; // Tells the frequenty of the PerformanceCounter. The value that the PerformanceCounter will increase each second.
double m_CounterTime; // The Counter of the PerformanceCounter.
double m_Trillingstijd; // How long one count of the performance counter will take.
public:
static cClock* GetClock();
cTime CurrentTime(); // Get the CurrentTime.
cTime LastTime(); // Get the LastTime.
// Virtual destructor.
virtual ~cClock();
protected:
// Protected constructor.
cClock();
};
// The clock cpp file
#include "Clock.h"
cClock* cClock::m_pClock = 0;
cClock* cClock::GetClock()
{
//BOOL perf_flag; // Timer Selection Flag
//double time_factor; // Time Scaling Factor
//LONGLONG last_time; // Previous timer value
//LONGLONG perf_cnt;
if (QueryPerformanceFrequency((LARGE_INTEGER *) &m_pClock->m_Frequency))
{
QueryPerformanceCounter((LARGE_INTEGER *) &m_pClock->m_CounterTime);
m_pClock->m_PerformanceCounter = true;
m_pClock->m_Trillingstijd=1.0/m_pClock->m_Frequency;
double LastedSeconds = m_pClock->m_CounterTime/m_pClock->m_Frequency;
m_pClock->m_LastTime.SetN(LastedSeconds*1000000);
m_pClock->m_LastTime.SetM(LastedSeconds*1000);
m_pClock->m_LastTime.SetS(LastedSeconds);
}
else
{
m_pClock->m_PerformanceCounter = false;
double LastedMiliseconds = timeGetTime();
m_pClock->m_LastTime.SetN(LastedMiliseconds*1000);
m_pClock->m_LastTime.SetM(LastedMiliseconds);
m_pClock->m_LastTime.SetS(LastedMiliseconds/1000);
}
return cClock::m_pClock;
}
cTime cClock::LastTime()
{
return m_LastTime;
}
cTime cClock::CurrentTime()
{
if(m_PerformanceCounter)
{
QueryPerformanceCounter((LARGE_INTEGER *) &m_CounterTime);
double LastedSeconds = m_CounterTime/m_Frequency;
m_CurrentTime.SetN(LastedSeconds*1000000);
m_CurrentTime.SetM(LastedSeconds*1000);
m_CurrentTime.SetS(LastedSeconds);
}
else
{
int LastedMiliseconds = timeGetTime();
m_CurrentTime.SetN(LastedMiliseconds*1000);
m_CurrentTime.SetM(LastedMiliseconds);
m_CurrentTime.SetS(LastedMiliseconds/1000);
}
m_LastTime = m_CurrentTime;
return m_CurrentTime;
}
This is my main, really simple but I just tried to get it to work but it doesn't...
#include "Clock.h"
#include<iostream>
using namespace std;
int main()
{
cClock* Clock = cClock::GetClock();
cTime Test = Clock->CurrentTime();
cout << Test.GetN();
cout << Test.GetM();
cout << Test.GetS();
int temp;
cin >> temp;
return 0;
}
It seems that the method cClock* cClock::GetClock() uses m_pClock without initializing it (it is still 0).
You are never creating an instance of cClock, just accessing a null pointer to one.
If you really think a singleton is a good idea, then cClock::GetClock() will have to create one if it doesn't already exist; along the lines of
cClock* cClock::GetClock()
{
if (!m_pClock) {
m_pClock = new cClock;
}
// remainder of function
return m_pClock;
}
Note that this isn't thread-safe, and also introduces a memory leak. Singletons are difficult to implement in C++, and best avoided unless there is a genuine reason for wanting one. I would move the logic of GetClock() into a public constructor, and allow client code to create and destroy clock objects as it sees fit.