So that's the easy way. Is there a better, more efficient way, or is this what would actually be accepted as good coding?
There is, and I've been working on a good example for some time now.
So that's the easy way. Is there a better, more efficient way, or is this what would actually be accepted as good coding?
There is, and I've been working on a good example for some time now.
Now the problem I'm having is how do I use a struct like Location Inn like you described above to give you different options depending on your location in the grid? I'm able to move around my grid from 1-10 in both the x/y directions, but that's all I've got so far.
You should have an if statement that takes into account many cases while you are moving (I'm assuming you're moving in a loop).
while(true /*or whichever condition you use to keep movement going*/)
{
//...
if(currentX == Start.x && currentY == Start.y)
{
//do something
}
//...
}
Assuming that you want to do it the fairly easy way.
Sorry I had that added for debugging purposes =P
#include <iostream> using namespace std; typedef struct Location { int x, y; Location(int col, int row) : x(col), y(row){} }; Location Start(2,2); int main(){ cout<< Location.start; cin.get(); }
I'm doing something wrong =\
Location is just a typedef for Locations. You can use the word Location to create coordinate objects, for example--
Location Inn(3, 4); //creates a location struct named Inn with x set to 3 and y to 4
Furthermore, the variable/function "start" doesn't exist in Location, and you cannot call Location in that way since its just a definition for anything that is that type.
In your above example, Start IS a location struct, so you can call upon its coordinates in this way--
cout << Start.x << ", " << Start.y << endl;
I think its because you assigned memory to a local-scoped T pointer in both constructors and not the actual variable in the private declaration. The local T must have masked the private T.
template <class T> list<T>::list() : size(5), newsize(size) //default
{
thelist = new T[list<T>::size]; //used to be T *thelist = new T[5]
numinlist=0;
}
template <class T> list<T>::list(int in_size) : size(in_size), newsize(size)
{
thelist = new T[in_size]; //same here
numinlist=0;
}
Okay, I think I get it now, the only question I have is what does the : x(col), y(row) - on part mean?
Pre-initialization - because the assignment operator causes a copy of the object to be made during the assignment, which can cause the program to do more work than it should.
Pre-initializing is considered good programming practice.
Yeah... actually now that I think about it, that sounds like it would work. I could do if(x=7, y=2){ type statements to represent towns, and increment/decrement x/y coordinates depending on which direction you pick.
I'm just not sure what the most efficient way to define the borders is, to make sure that the x/y coordinates won't get higher or lower than I want them to.
You don't need a 2D array of chars or anything else, just an array of structs and a starting-location for your character.
You'll probably also want to make a switch statement (or if statements) that handles the possible moves for the character.
typedef struct Location
{
int x, y;
Location(int col, int row) : x(col), y(row){}
};
Location Inn(4, 3), TrainingArea(2, 2), Gate(0, 4);
this doesnt make any sense. what's any of this got to do with Windows API?
you've got an 8x8 matrix of single characters... what meaningful information can you have in such a thing?
you should make an 8x8 matrix of a structure that describes every important aspect of any board position.
True. You can have a struct that holds the x and y information of the board.
Unfortunately I wasn't given enough information at the start other than the fact that the original poster wanted a map in a text-based RPG and wanted the characters capable of moving around in the array without going out of the bounds.
My first suggestion was a restricted array (or class) that would not allow the user to go out of bounds.
I also assumed that the original poster wanted to visually understand what was going on and had enough C++ experience to use file I/O and represent the map as a set of characters.
Oh I see. Well my original intent was to start with just a basic coordinate system, with no visible map displayed on the screen. As you move, it would display what square you moved to by outputting your coordinates. And the last feature I wanted was to have certain squares be represented by towns (and eventually dungeons), so for now I want to keep it simple until I've learned more in C++.
---|---|---|---
---|---|---|---
---|---|---|---
---|x | t |---x <- you are here. Then you're given the option to move north, east or west.
t <- town here. Step on this square and you'll get to do town things like store/inn.
Then you just want to display the numbers and maybe display the numbers of the valid locations to move to next?
In that case I really don't think you need arrays or file i/o. You just need to have predefined coordinates for places.
#include <iostream>
using namespace std;
template <class T>
class list
{
public:
list();
list(int);
void insert(T);
void remove();
bool empty();
void print();
~list();
private:
int size;
T *thelist;
int numinlist;
int newsize;
};
template <class T> list<T>::list() : size(5), newsize(size) //default
{
T *thelist = new T[list<T>::size];
numinlist=0;
}
template <class T> list<T>::list(int in_size) : size(in_size), newsize(size)
{
T *thelist = new T[in_size];
numinlist=0;
}
template <class T> void list<T>::insert(T write)
{
if(numinlist < list::size)
{
thelist[numinlist] = write;
numinlist++;
cout << "Numinlist is now" << " " << numinlist << endl;
cout << thelist[numinlist] << " " << numinlist << endl;
}
else
{
T *temp = new T[newsize];
for (int i = 0; i < newsize; i++)
{
temp[i] = thelist[i];
}
delete[] thelist;
newsize++;
T *thelist = new T[newsize];
for (int i = 0; i < (newsize - 1); i++)
{
thelist[i]= temp[i];
}
delete [] temp;
thelist[newsize - 1] = write;
numinlist++;
cout << "Numinlist is now" << " " << numinlist << endl;
}
}
template <class T> void list<T>::remove() //remove function
{
if(numinlist > 0)
{
numinlist--;
cout << "Numinlist is now" << " " << numinlist << endl;
}
else
{
cout << "List is empty" << endl;
exit(1);
}
}
template <class T> bool list<T>::empty() //detect empty function
{
if(numinlist == 0)
{
cout << "List is empty" << endl;
return true;
}
else
{
cout << "List is not empty" << endl;
return false;
}
}
template <class T> void …
Why would you want to fill up the array with chars though?
You're trying to display your map on the screen correct?
Doing so with characters is your best bet unless you're using Windows API and you're forming an application.
You'll have to give me more details on your program - I'm thinking that you're making a text-based RPG to be seen in the Console screen, so the first thing that came to mind were pre-placed characters from a text file.
Just 2, a chessboard with special squares (only bigger of course)
er, now that I think about it though, is it possible to have like dungeons or something that have their own specific map layouts?
Of course. It's your multi-dimension array, you can set it up any way you like.
You're going to want to do this the easy way... and when I mean the easy way I mean having your map already built in a .txt file then read the characters into a 2D char array...
#ifndef MAPXSIZE
#define MAPXSIZE 8
#endif
#ifndef MAPYSIZE
#define MAPYSIZE 8
#endif
typedef char MapArray[MAPXSIZE][MAPYSIZE] = {0};
MapArray firstMap, dungeon1Map, dungeon2Map; //... however many maps that you may need
//code to fill map with chars from .txt file
You could create a class that handles the boundaries of your multi-dimension array.
My question is this -- are you planning on having only 2 dimensions for the map or 3 in the event that you want to do some kind of map-switch?
Changed your constructor to initialize the size in this way--
template <class T> list<T>::list() : size(5) //default
{
T *thelist = new T[list::size];
numinlist=0;
newsize=5;
}
also changed your public static const variable to a private one--
private:
int size;
T *thelist;
int numinlist;
int newsize;
Then I made a change where you were doing constant damage to the heap, here--
newsize++;
T *temp = new T[newsize];
for (int i = 0; i < newsize; i++)
{
temp[i] = thelist[i];
//delete[] thelist //prior to edit
}
delete[] thelist; //after edit
where you kept deleting the same address over and over in your for loop.
Same problem occurs here--
T *thelist = new T[newsize];
for (int i = 0; i < newsize; i++)
{
thelist[i]= temp[i];
}
delete [] temp; //after edit
Also, you may want to place the incremented newsize after the copying of the values into the temp pointer, don't do it right off the bat--
T *temp = new T[newsize];
for (int i = 0; i < newsize; i++)
{
temp[i] = thelist[i];
}
delete[] thelist;
newsize++;
T *thelist = new T[newsize];
for (int i = 0; i < newsize; i++)
{
thelist[i]= temp[i];
}
delete [] temp;
Does that mean I need a new unique global pointer for each object I want to keep global?
Not necessarily. You could make an object global without making it a pointer, but it seems that you don't want a predefined "reference variable" that calls a particular constructor upon declaration, and furthermore you don't want to have a default constructor then call the member function of that variable at a later time.
If you don't want to mess with pointers, I'd suggest using the "reference variable" technique, otherwise you may have to deal with double pointers, or possible even a container like the vector class that holds character objects.
For example...
#include <vector>
vector<Character> charList; //vector that can hold character objects, declared at global scope
//... code to fill the vector via push_back(Character c)
I'd suggest studying vectors and staying away from double pointers, or you'll end up with a headache.
I can tell you the code for using double pointers, but it would be obnoxiously messy.
Here's a link for the vector class -- http://www.cplusplus.com/reference/stl/vector/
If I were to do that, how would I call my member functions with that object?
Also, I thought I didn't want to have to have the program call a member function to set the stats for my object. Maybe I misinterpreted what I was reading, but that seemed to be what the author was saying.
You would use pointer notation to call member functions, i.e...
cPtr->doSomething(); /*calling the method doSomething in the Character class the pointer is pointing to*/
--and as stated before, you did not call the constructor of the object until the case/break. Therefore your program wasn't directly calling a member function, but rather instantiating said object when "new" was declared.
If you are referring to the first question, I know it compiles, but I also know that doesn't necessarily mean it's right, was just looking for a confirmation that it's correct for a template, or no, you're missing stuff.
It's correct because you've generalized your list. That's one of the primary functions of templates - to make a general case for all valid objects/types.
Instead of only taking ints, it now takes anything that is a valid T parameter.
There are other reasons for templates, such as meta-programming and (supposedly) allowing a potential "bridge" for inheritance issues but from what I've heard the bridging isn't really a serious performance bump.
If you want an example of template meta-programming, consider the following code--
#include <cstdlib>
#include <iostream>
using namespace std;
class Fibonacci{
public:
template<int N>
inline unsigned __int64 series(){
return (this->series<N - 1>() + (this->series<N - 2>()));
}
};
template<>
inline unsigned __int64 Fibonacci::series<1>(){
return 1;
};
template<>
inline unsigned __int64 Fibonacci::series<0>(){
return 0;
};
int main(int argc, char *argv[]){
const int n = 6;
Fibonacci fib;
cout << fib.series<n>() << endl; //prints out the nth result of the Fibonacci series
cin.get();
return 0;
}
------ Build started: Project: AngleFinder, Configuration: Debug Win32 ------
Compiling...
SteveAngle.cpp
.\SteveAngle.cpp(85) : error C2296: '/' : illegal, left operand has type 'long double (__cdecl *)(const float)'
.\SteveAngle.cpp(88) : error C2297: '/' : illegal, right operand has type 'long double (__cdecl *)(const float)'
.\SteveAngle.cpp(119) : error C2296: '/' : illegal, left operand has type 'long double (__cdecl *)(const float)'
.\SteveAngle.cpp(122) : error C2297: '/' : illegal, right operand has type 'long double (__cdecl *)(const float)'
.\SteveAngle.cpp(151) : error C2297: '/' : illegal, right operand has type 'long double (__cdecl *)(const float)'
Build log was saved at "file://e:\Steve'sDocs\Visual Studio 2008\Projects\AngleFinder\AngleFinder\Debug\BuildLog.htm"
AngleFinder - 5 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Are you trying to divide using a divide char?
Or are you trying to divide by a floating-point value?
Is my question really that dumb that I get nearly 30 views and no replies...lol
You answered your own question.
Why not make a pointer to Character objects in global scope and then, based on the class the user suggest, instantiate said stats?
example...
//in global scope
Character *cPtr; //Notice your constructor isn't called yet
//when user inputs a char..
char classChoice;
cin>> classChoice;
switch(classChoice)
{
case 'W':
case 'w':
cPtr = new Character(/*Warrior stats here*/);
break;
case 'M':
case 'm':
cPtr = new Character(/*Mage stats here*/);
break;
default:
cout << "Improper selection" << endl;
break;
}
Actually the subject that I am doing the thesis has nothing to do with programming or software. The subject is called something like: Environmental Protection. And the application will have to be a system that monitors the materials that Industries use and the wastes that they produce. Since one industry's waste could be used by another industry for material, there should be a network with all the industries and I will have to deterine which one needs what from whom.
It is easy to be done in java, but since the lab that the professor runs consists mostly of chemists, the only thing they know is VB and access.
So he wants it to be done in VB in order for the application to run with the other programs they have.
Besides I shouldn't have a problem learning a new language. I just wanted a good book to get me started, based on my java background.
From what I saw, VB is fairly adjacent to Java, except that it is easier.
My friend took a VB class and from what I noticed (with less Java experience than you) is that a lot of what they do deals with manipulating Windows. A lot of the code looks like Java "inner classes" with commands (sort of like built-in action listeners / executors), etc.
The only thing you'll really have to know is the syntax and of course a library to use the functions. I'd suggest looking up …
Ok thanks I think I understand my previous question but another question are the values "3" and "4" or "5" and "6" stored in any specific variable?
Like if I wanted to show the "3" and "4" can I write a line
cout <<specificvariable;
what would that specificvariable be?
If you want to display the individual variables, you will have to understand that calling rect.x or rectb.x and rect.y and rectb.y are illegal calls since classes are initialized with private member variables until you provide public access members/functions.
If you want to get a specific variable, you'll need to provide a public "getter," like this--
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
int getX(){return x;};
int getY(){return y;};
};
Now for rext and rectb you can call getX() and getY() with cout to display their respective x's and y's--
cout << rect.getX() << ", " << rect.getY() << endl;
cout << rectb.getX() << ", " << rectb.getY() << endl;
CRectangle rect, rectb;
rect.set_values (3,4);
rectb.set_values (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
rect and rectb are 2 different variables that are of the same class-type.
to make the code more understandable it might be better for you to do something like this--
CRectangle rect; // a CRectangle reference-variable named rect
CRectangle rectb; // a CRectangle reference-variable named rectb
rect.set_values (3,4);
rectb.set_values (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
MySuperType mytype = null;
if (sub_type) {
mytype = new MySubType (); //should be ok
mytype.setD(4);
mytype.setE(5);
} else {
mytype = new MySuperType (); //Most likely a compiler error
}
mytype.setA(1);
mytype.setB(2);
mytype.setC(3);
When you do something like--
Object obj = new String("Upcasted!");
--it is called upcasting. String is a derived form of an Object, so this code is valid. However the reverse shouldn't be true--
String str = new Object() // WRONG!
--Because Object can contain data of any derived type, like we have shown above. It may be possible that the data stored in the Object has nothing to do with the data in the String class. Now if you do this--
String str = (String)new Object(); //Not quite right
--you're downcasting the object from its current type to a type it might consist data of. Since it's a new Object it is impossible to have data of a String object since the term "data" really depends on the creation of the object (during the constructor call).
When you create a String for example, there's a constructor call to String's super constructor - Object. Therefore String has data of Object, and when the Super constructor finishes execution, Strings constructor finishes execution as well so it additional contains data of a String.
This means that String can be supercast into an Object type (for whatever purpose you need to supercast), but an Object cannot always be downcast into a String (because it's …
thanks... u can edit ur quote as well if u would like. :)
I'll keep it as-is for the record XP
Whats important is that you made the change =)
haha Narue you're a funny guy, i'm not so bad at picking out the experts and arrogant individuals either. Thanks anyways for the link.
Better edit this quick... Narue is a woman =P
>So your telling me what is being displayed on my windows
>screen is the output of a combination a C++ program?
I'm telling you that the Windows operating system is written in a combination of C and C++. Most of the programs you run are as well.>but howwwwwwwwwwwwwwwwwww :O
Not to be rude or anything, but if you're as new to programming as it seems, you won't get it even if we told you. There's a lot of prerequisite knowledge that comes with understanding how non-trivial programs are written. As you learn more about programming and C++, you'll gradually come to an answer.
Even after 3 quarters of Java and researching c++ extensively as well as coding... I am at the point where I need to learn the UML and at the moment it seems like I'm mixing beans with pickles..
I totally understand what you mean by that bolded comment. When I started looking into UML's I realized that projects are just ideas from one person... they're thought out not just before the design but during the design and even after the design.
Its no wonder that new versions of programs come out fairly quickly.
I have a program with a bunch of threads running. I kill them all at the end of the program. I have stepped through and seen them all abort. Is there a way to see (since I cant when stepping through) which thread it is? I can see the process in my task manager, anyway to get more info on it? Thanks.
Can't you make each thread do something (like every second) and watch them die?
For example, print a number onto the console screen?
IF you know C# then you will have little difficulty converting it to java on your own. It will not take you much time to read a few things about java. If you know C# you don't need to learn anything new, just understand a few things about how java works.
If you know C# and you didn't just find someone else's code and you want to convert it to java for your assignment.
Yeah I agree...
Knowing C# takes some fair Java and C language know-how, along with the idea of delegates, partial classes, unsafe context, "member variables," etc...
Hi guys,i am new to both c++ and this forum...I got a problem with a question i m supposed to do.I am supposed to create a queue system but i am stuck at a point where i can't add numbers to the queue system.This is the question...
You have been assigned to code the world longest queue that can store up to a maximum of 10 integers.Create a queue system interface with the following functionalities:
- option to Add number to end of queue
- option to Remove number from end of queue
- option to Sort queue in ascending order
- option to Show queue content
- quit
Sample Output:Queue System [Free: 10]
==================================
1. Add number to end of queue
2. Remove number from end of queue
3. Sort queue in ascending order
4. Show queue content
5. Quit
Choice: 1Enter the number to add: 10
The problem is that i can't add number to the queue.Here is my code...
# include<iostream> using namespace std; void show(int a[],int size) { for(int b=0;b<=size;b++) { cout<<"Item "<<b<<": "<<a[1]<<endl; } } void subno(void) { int sub=0,b=0,c=0; cout<<"Status: Last number successfully removed."<<endl; } void addno(void) { int arr[10]; int b=0; cout<<"Enter number to add: "; [B]for(int i=0; ;i++)[/B] { cin>>arr[i]; } } void main(void) { int b=10,c=0,e=0; int a=0; do { cout<<"Queue system [Free:"<<b<<"]"<<endl; for(int f=1;f<36;f++) { cout<<"="; } cout<<endl; cout<<"1. Add number to the …
Odd, I'm not getting that error at all...
Did you include the preprocessor directives for cstdlib and iostream? Also are you using namespace std?
It ran fine for me, no weird operator errors.
This is an example of recursion.
When you send the number 5 into the method simpleMeth() it will call the method simpleMeth(4) before reaching the print statement. Then simpleMeth 4 will call simpleMeth(3) before it reeaches the print statement.
This process will continue until simpleMeth reaches 0, where it will return the current status of i - in this case 0 is first printed... now that the simpleMeth(0) method is finished executing, the method before it (simpleMeth(1)) will finish executing and print 1...
This process keeps going until finally the initial method is done executing.
Keep in mind that a method has to perform functionality before execution ends. If you were to change the code such that println came before the decremented method call you would see the reverse process since the print statement occurs before the recursive method is called.
Hello everybody,, this is a simple java method that calls itself,,
class ex{ public static void main(String [] args){ simpleMeth(5); } static void simpleMeth(int i){ if(i != 0){ rec(--i); System.out.println(i); } } }
If you follow the the codes you will find after sending number (5) to the method then will be tested by the if statement(line n.6) then comes again to the method(line n.7) so (i) will be 4, and will continues until (i) equals 0,,but why after ending the if statement and comes to the method end brace,returns again to the printing statement and printns (0) then goes to line n.10 and adds one to (i) and returns again to line n.8 and so until (i)equals 4 ..
the result is:
0
1
2
3
4Hope understand what i mean :)
Thnx..
Where is rec defined?
if(i != 0){
rec(--i);
You didn't post all of the code =/
I am studying stacks, queues, and heaps at the moment but i dont know how i can apply this in real life. Well my question is how can these may i say operations helpful and when are they really needed as opposed to others. I hope you can get my question well. Thanx a bunch
If you need an easy way to relate to the data structures, you can think of a Queue as a type of line to wait in...
for example, when you're at the grocery store (or any place that gives some type of customer service) you're considered to be in a Queue-based system. If you were the first person in line, you are the first person to be served.
On the other hand, Stacks are Last-in first-out. Many businesses would not be successful if their lines were based on a "stack" system, even though it would be crazy funny to see people trying their hardest to be last in line just so they could be served first while people who came first would be waiting forever (or close to it).
A good example of a stack would be a set of heavy boxes. You stack one heavy box on top of another, and realize the first one (on the ground) is impossible to lift, so your best bet to be productive with the boxes it to remove the lightest one, which should always be the one on the top of the stack - …
Hi all,
Thanks for your help so far ! I hope you wont mind if I ask you for help again..Being brutally honest I must admit that I didnt study the later material of the course properly what now effects in huge lacks in my knowledge...:'( after the Map and other Collection interface, the Streams have been introduced. I understand the whole concept of using them but I really struggle when it comes up to writing the method. I will post what I have come up with but am aware there are a lot of mistakes. I would appreciate if someone could check it and point me to the right direction.(the class OUFileChooser has been provided by the university)
The question:
Consider the following method comment and header defined for a
hypothetical class called FrogIO.
/**
* Prompts the user for a pathname which is then used to create a File
* object. The method then attempts to open a stream on that file.
* The method then writes the details of the frogs held in the argument
* frogCollection to the stream in CSV format
*/
public static void saveStateOfFrogs1(Collection<Frog> frogCollection)
Write the code for this method. Your code must make use of the File and
FileWriter classes. To achieve full marks your solution should make
appropriate use of buffering, inform the user of any exceptions that might
occur, and include a finally statement to ensure that …
Can you post the rest of your code? I have a feeling it has something to do with the way you've created your primHashTable class.
Maybe you should try leaving out the parenthesis?
Also, why aren't you posting the error? You should at least do that if you want people on here to help X_X
Thanks Alex,
I now understand how virtuals work, i thank you very much for your effort.
And one more question: So can virtual fuctions actually perform actions when they are not overwritten?Thanks in advance,
Tigran
Only if they aren't pure virtual.
Virtual functions mark the function declared to be overwritten by a class such that the method will perform the functionality of the derived class when the base class is called...
For example...
#include <cstdlib>
#include <iostream>
using namespace std;
class ToString
{
public:
virtual char *className(){return "No Name Set!";};
};
class Person : public ToString
{
private:
char *myName;
public:
Person(char *nameArg){myName = nameArg;};
char *className(){return myName;};
};
int main()
{
Person matt ("Matt");
ToString *ts = &matt;
cout << ts->className() << endl;
cin.get();
return 0;
}
This should print out "Matt," despite the upcasting of Matt into ToString.
This is because we marked the method of className() in the base class virtual- a derived class's data that overrides the method with the same name and arguments will, at runtime, force the base class to call the derived class's method.
This is particularly useful if we want to make an array (or pointer) to objects of many types and we only want to call one method to perform various kinds of functionality.
Hi guys,
1) Why do some people set a "_" before things like function names?
I've seen this a few times, and asked myself if it had or didn't have any use.
A lot of this _class naming is done for library purposes, but it isn't restricted to that.
2) For this one, you should look at a simple code:class TutorialApplication : public ExampleApplication { protected: public: TutorialApplication() { } ~TutorialApplication() { } protected: void createScene(void) { } };
First i'd like to say that this isn't my code, second i'd like to say that somewere in the source code there is a class definded with the name ExampleApplication.
Now comes my question:
As you can see in the first line, after class TutorialApplication comes something else.
but what is the function of that? It confuses me.
the : denotes an extension from another class. Since TutorialApplication extends from ExampleApplication, it will inherit all of the public and protected member fields of ExampleApplication and can be used as an ExampleApplication object.
3) My last question:
as you can see, there are 2 public functions defined:
TutorialApplication()(which i think is a constructor)
But there is also "~TutorialApplication()" which confuses me, what does it do? i mean with that strange "~" which i've seen for the first time...
The tilde ~ by the classname (like a destructor) denotes a Destructor. a Destructor is called when the delete operator or ~ObjectName::ClassName() …
Hello,
I'm getting a compile-time error in jdk1.2.1 which says "Identifier expected" and points to this line in the code:
Vector<Fish> fishes = new Vector<Fish>();
Aren't vectors supported in jdk1.2.1? I'm unable to catch the problem.
Vectors may be supported in jdk, but they may not be supported with Generics.
Try--
Vector fishes = new Vector();
Or update your development kit to a more recent version.
A note regarding clipboard usage, whenever you successfully open the clipboard, don't forget to close it by calling CloseClipboard() when you're done with the clipboard operations.
I swear to god I'm starting get my coding confused after seeing that...
Feels like CSharp when you use uppercased methods, when really it's C++...
Or maybe it's not, since I've heard that the Windows API isn't meant specifically for the C language.
Hi,
Will casting one of them also take care of the larger numbers?
Thank you,
Why not just make your factorial method return a long?
Edit: denominator will also have to be declared a long and not an int, since you're assigning denominator the value returned by the factorial method.
term = static_cast< double >((numerator/denominator));
is evaluating the double after doing int division within the cast. Try--
term = static_cast< double >(numerator)/denominator;
ahhh I see.
Now if I wanted to call pedal from cycle, but within bicycle, I think I can do it by just putting cycle::pedal(); in bicycle's member function pedal. Is there another way to do it? (I did this in a door class with a door open member function, but I'm told it can be done another way)
Indeed, within the class you can use cycle::pedal(), but I think you can also use the this modifier to point to the base object--
this->pedal()
--though they both should mean the same thing. Using one or the other is entirely up to you, but I prefer the Base::functoname() method much better since it's more intuitive imo.
If I'm getting this, the call from main would look something like
cycle * cycleptr = new bicycle;
pedal (cycleptr);Would that be correct?
No, because your namespace has no method named pedal defined and also the method pedal in your base and derived classes has no parameters.
replace pedal(cycleptr) with either--
cycleptr->pedal();
//or
(*cycleptr).pedal();
3.6 * vector_a; why can I not implement this binary operator as a member operator of a class Vector?
class cycle { cycle(); ~cycle; pedal(); }; class bicycle { bicycle(); ~cycle; pedal(); }; bicycle *bikeptr = new bicycle; cycle cycleptr=dynamic_cast <cycle>bikeptr; cycleptr->pedal();
Your pointer is given a valid bicycle address (and of course the potential to store information big enough for a bicycle).
Now you're trying to cast it into an instantiated variable of cycle, which I am not entirely sure will work out too well. Instead you may want to assign the address of bikeptr to a cycleptr--
cycle *cycleptr = reinterpret_cast<cycle*>(bikeptr);
cycleptr->pedal();
//and yes, this is in main =p
Okay, so as written, cycle's version of pedal is used. If I put the word virtual in front of it, then bicycle's version is used?
Correct.
To test this first run the program after putting something along the lines like--
cout << "I am BASE" << endl;
in your base's method and then
cout << "I'm a DERIVED" << endl;
in your derived method to understand this.
Alex, thanks for responding. First, I'm more than willing to explore doing it your way with the vector, but can you tell me why it doesn't work the way it is now?
Now if I understand what you're saying, it will call the cycle version of pedal for my first virtual question? I thought it would call bicycle's version.
In question 2, I thought maybe putting the virtual keyword in front of pedal would "force" it to use cycle's pedal function, but I don't know how to do that for bicycle.
In question three, again I thought maybe this was done in the cycle class by putting virtual before pedal, and "=0" after the ().
and then the question still remains, how is it called in main?
I'm not too sure about the vector class, but it could be that vector doesn't have an operator defined to multiply all components by a scalar. I'm aware of the initialization constructor but not of this operator (Im still new to c++ but I know at least this much =P ).
And about the virtual function... before looming over the keyword, consider what's happening between your classes.
Your Base class is its own object. The Derived class is an instance of Base and has additional data. The Base class is like a father who knows he has children but doesn't know where they are, and won't acknowledge them even if you told Base class they were its children. Derived class, however, …
For your first question, why not make a class that extends from the vector class and overload the binary operator in your extended class to do the scalar-to-vector multiplication you want?
Also, because your cycle method in your base class isn't virtual, it will call its own method of cycle, not bicycles.
If you want polymorphic behavior, where your base class only uses one method that executes data of an extended classes method of the same method name you'll have to mark your base class' method to virtual.