C++

57K

Solutions

24K

Contributors

C++ is an intermediate-level general-purpose programming language, not to be confused with C or C#. It was developed as a set of extensions to the C programming language to improve type-safety and add support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.

Share tech news, updates, or what's on your mind.

Sign up to Post

I have three base Classes {Player,Weapon,Game} and one inherited Class Warrior from Player.

I would like to code function addWizard using function .I thought of dymanic casting,but I'm not sure how to start. Any help would be appreciated.

Notes:

*Each index in playersArray consists of pointers to class Player.

*If a player's name in a given index,oplayersArray equals to empty string, it indicates there's no player yet.

*I added the constructors of each Class Game and Player(the default only) and Wizard.

void addWizard(string const& playerName,string const& weaponName,
                       Target target, int hitstrength,int range);

GameStatus Game::addPlayer(const string playerName, const string weaponName,
                               Target target,int hit_strength)
    {   int count=0,place=0;
        if(this->countPlayers()>=maxPlayer)
        {
            throw GameFull();
        }
        for(int i=0;i<maxPlayer;i++)
        {
            if(playersArray[i]->getPlayerName()!="" &&
               playersArray[i]->isPlayer(playerName))
            {
                throw NameAlreadyExists();
            }
            if(playersArray[i]->getPlayerName()==""&& count==0)
            {
                count++;
                place=i;
            }
        }
        Weapon newWeapon(weaponName,target,hit_strength);
        Player newPlayer(playerName,newWeapon);
        *playersArray[place]=newPlayer;
        return SUCCESS;
    } 

Open in new window


Classes:

class Game {
        int maxPlayers;
        Player **playersArray;
}

class Player {
        string player_name;
        int level;
        int strength;
        Weapon player_weapon; }

//the inherited Class 

class Wizard : public Player {
    int range;
public:
    Wizard();
    Wizard (string const& name, Weapon const& weapon, int range);
}

Open in new window

Constructs:
Game::Game(int maxPlayer)
: maxPlayer(maxPlayer),playersArray(new Player*[maxPlayer])
{
    for(int i=0;i<maxPlayer;i++)
    {
        playersArray[i]=new Player;
    }
}

Player::Player():
        level(0),life(0),strength(0),place(0),player_name()
{
}

Wizard::Wizard(string const& name, Weapon const& weapon, int range) :
        Player(name,weapon),range(range){
    if (weapon.getTarget() == LIFE){
        throw IllegalWeapon();
    }
    if(range<0)
        throw InvalidParam();
}

Open in new window

0
Free Tool: ZipGrep
LVL 12
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Hello

is there a way to set gdb filename:line_number such that the filename is a path?

thanks
0
std::function as a parrameter in delegate constructor
      i want to know why control does not goes to AB() if i passed abc(AB) in main() as control goes for initialization of i as 10 when abc(10) is passed

class abc { int i;

    std::function<void(void)>func = nullptr;
public: abc(){}
    abc(std::function<void(void)>&fb):func(fb){}

    abc(int i):i(i){}
};
void AB() { cout<< "fun_AB"; }

int main() { abc(AB); abc(10); }

Open in new window

0
Good day! I'm trying to display an image in the Picture Control in the MFC with pixel data. Tell me what's wrong.

image = new DicomImage(str);
		
		image->setMinMaxWindow();
		Uint8 *pixelData = (Uint8 *)(image->getOutputData(8));
		if (pixelData != NULL){
			int w = image->getWidth();
			int h = image->getHeight();

			HBITMAP hBitmap = NULL;

			BITMAPINFOHEADER bmih;
			bmih.biSize = sizeof(BITMAPINFOHEADER);
			bmih.biWidth = 1024;
			bmih.biHeight = -512;
			bmih.biPlanes = 1;
			bmih.biBitCount = 8;
			bmih.biCompression = BI_RGB ;
			bmih.biSizeImage = 0;
			bmih.biXPelsPerMeter = 10;
			bmih.biYPelsPerMeter = 10;
			bmih.biClrUsed = 0;
			bmih.biClrImportant = 0;

			BITMAPINFO dbmi;
			ZeroMemory(&dbmi, sizeof(dbmi));  
			dbmi.bmiHeader = bmih;
			dbmi.bmiColors[0].rgbBlue = 0;
			dbmi.bmiColors[0].rgbGreen = 0;
			dbmi.bmiColors[0].rgbRed = 0;
			dbmi.bmiColors[0].rgbReserved = 0;
			void* bits = (void*)&(pixelData[0]); 

			// Create DIB
			HDC localDC = ::GetDC(NULL);
			hBitmap = CreateDIBSection(localDC, &dbmi, DIB_RGB_COLORS, &bits, NULL, 0);
			if (hBitmap == NULL) {
				::MessageBox(NULL, __T("Could not load the desired image image"), __T("Error"), MB_OK);
				return;
			}

			unsigned char* dest = new unsigned char[w*h];
			dest =	(unsigned char*)bits;
			const unsigned char* src  = pixelData;
			for (int j=0; j<w; j++){
				for (int i=0; i<h; i++, src++){
					*dest++ = *src;
					*dest++ = *src;
					*dest++ = *src;
				}
			}	

			

Open in new window

0
how to get the SwapTotal for solaris in C or C++?
0
Hi,
I am making a Doodle Jump game in c++ using sfml,
I started building the umlaut and decided to go with a STRATEGY pattern. I don't really know if this is the right choice.
I basically got to a point where I don't know how to continue,
please if someone could take a look at my UML and tell me what they think it will be greatly appreciated.



0
I have a DLL that is simply using some pretty common code to count files in a directory. On all our test computers, and 98% of people using it, there is no problem. But a few people experience a crash to desktop from this code. I am looking for some possibilities of why this could happen in these isolated cases.

Here is the code:
int FMSGaugeCallback::getFltPlnsInFolder(wchar_t szPath[MAX_PATH])
{
	WIN32_FIND_DATA		ffd;
	wchar_t				szFileName[MAX_PATH];
	HANDLE				hFind = INVALID_HANDLE_VALUE;
	DWORD				dwError = 0;
	wchar_t				szError[255];
	wchar_t				szDir[MAX_PATH];
	int					nLen = 0, nDir = 0, nCount = 0;

	if (!PathIsDirectory(szPath))
		return 0;

	PathAddBackslashW(szPath);
	swprintf(szDir, sizeof szDir,  L"%s*.pln", szPath);
	hFind = FindFirstFileW(szDir, &ffd);								// Open filefind
	if (INVALID_HANDLE_VALUE == hFind)								// if process fails record error
	{																// and discontinue function
		dwError = GetLastError();
		swprintf(szError, sizeof szError, ERR_SEARCH_FLT_PLNS, szPath,getLastWinError(dwError));
		writeToErrorLog(szError);
		return 0;
	}

	do																		
	{																		
		if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)					
		{
			nDir++;															// the flight plan array
		}
		else
		{//-
			nCount++;
			
		}//-
	} while (FindNextFileW(hFind, &ffd));

	FindClose(hFind);												// Close filefind
	return nCount;
}

Open in new window


It is crashing in the do while loop, not at FindFirstFile.

Any ideas?
0
ardunio on board memory manipulation have a arduino mega now what is the best way to do the following, i want to have the program running and then update the array on board the arduino with out reloading the program, so lest say i have an array with 10 numbers and depending on the feed back from the card i am going to change location #4 of the in the 10 mem locations that i have set up how is the best way to do this please from the code running on the pc , would i access the arduino then the mem location and go from there, any ideas in this correct direction would be helpful
0
I had this question after viewing Explorer.exe crashing.
Hi, I have a simular issue on Windows 2016 Server RDS. I however do not have Microsoft Visual C++ 2008 installed but I do have the x86 and x64 versions of 2010 and 2012 installed. Do you suggest that is is a general issue with the Microsoft Visual C++ software of specific for Microsoft Visual C++ 2008?

Error:
The program iexplore.exe version 11.0.14393.2007 stopped interacting with Windows and was closed. To see if more information about the problem is available, check the problem history in the Security and Maintenance control panel.
 Process ID: a54
 Start Time: 01d3ec5f951cd3ff
 Termination Time: 8
 Application Path: C:\Program Files (x86)\Internet Explorer\iexplore.exe
 Report Id: e0176242-5852-11e8-90fe-001dd8b74bda
 Faulting package full name:
 Faulting package-relative application ID:
0
Unable to Debugg C++ ATL dll in C# . The ATL dll is not getting loaded. C# aplication is loading a interop but no pdb for interop is getting created.
Please let me know how to resolve this issue.
0
Cloud Class® Course: Microsoft Exchange Server
LVL 12
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

https://m.youtube.com/watch?v=4UKkuO9iuq8

I am new to qt creator. The video shows a secondhand moving smoothly . QT creator comes with demos with secondhand ticking once per second. Can you point me to some code that will rotate a line around the center point as smooth as in that video and at varying speeds maybe ?
0
hello

i m a begineer in Qt based GUI development..
i m developing one simple gui based on am-5728 ti sitara arm cortex EVM board..

in my GUI app. i want to use pushbutton function link to the hardware gpio pushbutton.
means i can select that push button through pressing hardware button.
but cudnt link the event of hardware to my Qt app.

can u please suggest me the solution regarding this in Qt how to link both app to hardware button..


waiting for your valuable reply..

regards
Hardik
0
Dear All,

Can anyone have idea on mattermost webRTC integration. I am getting error while connecting video calls.

Thanks
0
using Visual Studio Web Page.  I have a DataGridView with a checkmark box in the 11th column.  I want to color the row red if checked..  here is the code I have found to do this but nothing is happening.  THANKS

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        CheckBox chk = (sender as CheckBox);
            if (chk.ID == "chkALL")
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    row.Cells[10].Controls.OfType<CheckBox>().FirstOrDefault().Checked = chk.Checked;
                    row.BackColor = System.Drawing.Color.Red;
                }
                else
                {
                    row.BackColor = System.Drawing.Color.White;
                   
                }
 
            }
        }
       
    }
0
Using Visual Studio 2010 Pro at work. That is, using C++03.

In this article https://www.experts-exchange.com/articles/3183/An-Introduction-to-STL-Algorithms.html is the code:
#include <iostream>
#include <list>
#include <iterator>
#include <algorithm>

int main()
{
    std::cout<<"Creating intList with values 0-9.\n";
    std::list<int> intList;
    for (int i = 0; i < 10; ++i)
        intList.push_back(i);
    
    std::cout<<"Displaying values held in list before modification:\n";
    std::copy(intList.begin(), intList.end(), std::ostream_iterator<int>(std::cout, " "));
    
    std::cout<<std::endl<<std::endl<<"Using find_if with unary predicate to display odd list items.\n";
    while (true) {
        std::list<int>::iterator found = std::find_if(intList.begin(), intList.end(), std::bind2nd(std::modulus<int>(), 2));    
        if (found != intList.end()) {
            std::cout<<"Found even #: " << *found <<". --> Removing it now"<<std::endl;
            intList.remove(*found);
        } 
        else
            break;
    }
    
    std::cout<<std::endl<<"Displaying values held in list after modification:\n";
    std::copy(intList.begin(), intList.end(), std::ostream_iterator<int>(std::cout, " "));
    
    std::cout<<std::endl<<std::endl<<"Replacing values that are divisible by 4 with 99.\n";
    std::replace_if(intList.begin(), intList.end(), std::bind2nd(std::modulus<int>(), 4), 99);
    
    std::cout<<"Displaying values held in list after 

Open in new window

0
This is how my program looks like:
_RecordsetPtr pRsUser = NULL;
if (m_AccessRepositoryMgr.Get_UserByName (&pRsUser, sName))
{
//dosomething;
}

/** User stub definition for function: bool CAccessRepositoryManager::Get_UserByName(_Recordset **, const CString &) */
bool (::CAccessRepositoryManager::CppTest_Stub_Get_UserByName) (::_Recordset ** ppUserList, const ::CString & sName)
{
bool __return = true;
return __return;
}

Here I want to set the value in ** ppUserList such that upon return from User stub function, in the code pRsUser should not be NULL.
0
Hi Experts,

          I am using  ITaskSchedular interface to retrive the Last runtime of the task scheduled. Code is working fine upto windows 7 using visual studio 2010. PLease suggest the way to make it working in windows 10.Link for source code is as given below:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa446844(v=vs.85).aspx


GetMostRecentRuntime() hr shows the task has been not run yet.(I already run the task .)


Thanks in advance.
0
void mainImage( out vec4 fragColor, in vec2 fragCoord ) 
{
    vec2 px = vec2(1.0) / iResolution.xy;
    vec2 pos = fragCoord.xy / iResolution.xy;
   
    vec4 color =  texture(iChannel0, pos);
    vec4 origColor = color;
    float numSamples = 1.0;

    {
    	for (float x = -8.0; x <= 8.0; x += 1.0)
    	{
        	for (float y = -8.0; y <= 8.0; y += 1.0)
    		{
	        	vec4 addColor = texture(iChannel0, pos + (vec2(x, y) * px));
                if (max(addColor.r, max(addColor.g, addColor.b)) > 0.3)
                {
                    float dist = length(vec2(x,y))+1.0;
                   // if (dist <= 5.0)
                    {
                        vec4 glowColor = max((addColor * 128.0) / pow(dist, 2.0), vec4(0.0));
                        if (max(glowColor.r, max(glowColor.g, glowColor.b)) > 0.0)
                        {
                			color += glowColor;
            				numSamples += 1.0;
                        }
                    }
                }
        	}
    	}
    }
    
    fragColor = mix(origColor, color / numSamples, 0.05);
    fragColor.a = 1.0;
}

Open in new window


Could you help me in converting this shader to #version 120 pleasee?
0
The Arduino programming appears to be C++,  don't know what flavor.
I can open the files with VisualStudio and it let me edit the code.

VS does not recognize the reserved object "String" that can not only be used to declare string variables, but used for conversions as well.

Can I simple #include the library that contains the "String" class and proof my Arduino code in V.S. ?
Any Idea where this library is ?

Thank you.
0
Free Tool: Subnet Calculator
LVL 12
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

I am going to quote converting an RM Cobol program to C++ or C#. One of the issues is that it needs to access some ISAM type files. So, which compiler should I recommend and do they have libraries available to access this type of file?
Its only about 300-500 lines of code.
0
I need to read any type of file
encode it using huffman
decode it using huffman
MD5  Sum should match after decoding

only condition is the encoded file should have less size than original file
can anyone help me with that it can be done in java or C++
0
For my MS C++ application, I want to add text-to-speech, and then perhaps speech-to-text later.  Is there any reason to use something other than Microsoft Speech Platform?    Some other toolkit SDK that would somehow be more advantageous?   Thanks!
0
I'm trying to get away from trusted sites in IE.  I have a too many GPO's as it is and booting up takes forever.  I've noticed that trusted sites takes a long time to load and I was wondering if there was a better solution...  I'm trying to avoid the sites loading again and again every time a machine reboots.  Would it be better to create a gpp for registry setting for trusted sites?
0
Dual pipe producer/consumer blocked by read.

The issue is in the producer:
        read(consumer_to_producer[0], &cnt, sizeof(cnt));
        read(consumer_to_producer[0], shared_arr, sizeof(shared_arr));

Open in new window

prevents the producer from working because the consumer has yet to write anything, how can I avoid this?


#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10

int shared_arr[SIZE];
int cnt = 0, in = 0, out = 0;
int consumer_to_producer[2], producer_to_consumer[2];

void consumer();
void producer();

int main() {
    pipe(consumer_to_producer); // consumer to producer
    pipe(producer_to_consumer); // producer to consumer

    if (fork() == 0) {
        /* child process */
        consumer();
    } else {
        /* parent process */
        producer();
        sleep(3);
    }

    exit(0);
}

void consumer() {
    /* consumer process */
    close(producer_to_consumer[1]); // Close write end, we don't need it
    close(consumer_to_producer[0]); // This fcn doesn't need read end
    while (1) { 
        /* if buffer is full, consume it */
        // read in cnt from producer so we can check if it's full
        read(producer_to_consumer[0], &cnt, sizeof(cnt));

        if (cnt == SIZE) { /* If full, consume */
            read(producer_to_consumer[0], shared_arr, sizeof(shared_arr));
            printf("I am consuming\t%d\t%d\n", shared_arr[in], out);
            out = (out + 1) % SIZE;
            cnt--;
        } 

        

Open in new window

0
Hi,
I'm trying to create a map of <string, pointer to a function> where the functions signature may vary (all of them return int, bu may take arguments of different types). All the functions are template functions.
I'm using a multimap of <string, std::function<int(boost::any*)>*>, but when I'm trying to instantiate a function with type boost::any i'm getting a compilation error.

I wonder if there is any neat solution or bypass.
Thanks.
0

C++

57K

Solutions

24K

Contributors

C++ is an intermediate-level general-purpose programming language, not to be confused with C or C#. It was developed as a set of extensions to the C programming language to improve type-safety and add support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.