Basic pointer to array of class for c++ - c++

AIBase* allai[2];
AIBase *z0AI = new AIA;
AIBase *z1AI = new AIB;
allai[0] = z0AI;//this this gives me an error
allai[1]= z1AI;
AIBase is the superclass and AIA and AIB inherits from the AIBase
what is wrong with the syntax ,i need some help in figuring this out
error 1:
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2466: cannot allocate an array of constant size 0
error C2040: 'allai' : 'int []' differs in levels of indirection from 'AIBase *[2]'
Why must this code be in function scope? Cant this work in global scope?

In C++ (and C), executable code that is not a variable initialiser must appear inside a function. Executable code cannot appear at file scope (that is, outside any function).
So, just put your code inside a function:
int main(int, char *[])
{
AIBase* allai[2];
AIBase *z0AI = new AIA;
AIBase *z1AI = new AIB;
allai[0] = z0AI;
allai[1]= z1AI;
}

Related

Passing a class pointer as a function argument

Currently I am trying to create a function to implement modularization in the code like below.
[Code 1]
float CBitmapWaterMark::DrawPrintInfoText(HDC hDC)
{
StringFormat* stringFormat = new StringFormat();
// I'm trying to pass a stringFormat object to a member function of a class(CBitmapWaterMark).
stringFormat->SetAlignment(StringAlignmentNear);
stringFormat->SetLineAlignment(StringAlignmentNear);
TestFunction(stringFormat) //help point 1
}
VOID CBitmapWaterMark::TestFunction(StringFormat* stringFormat) // help point 2
{
// implement
}
=> Syntax Error identifier StringFormat
But I don't know how to pass it as a function argument and how to receive it.
There seems to be a problem with StringFormat which is declared in <gdiplusstringformat.h>.
This is a minimal complete reproducible example:
#include <windows.h>
#include <gdiplus.h>
#include <gdiplusstringformat.h>
StringFormat fmt;
Error log:
1>C:\Project3 C++\main.cpp(5,17): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>C:\Project3 C++\main.cpp(5,14): error C2146: syntax error: missing ';' before identifier 'fmt'
You'll need a using Gdiplus::StringFormat. The name "StringFormat" is fairly generic, so C++ has namespaces to prevent name collisions between 2 libraries. GDI+ puts its names in namespace Gdiplus.

Assign value to dynamically allocated integer

UPDATE:
Thanks to everyone for the help to understand this!
I try to run this:
#include <iostream>
int* x = new int;
*x = 5;
int main()
{
}
and i get the following errors:
1>------ Build started: Project: learnCpp, Configuration: Debug Win32 ------
1>learnCpp.cpp
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,6): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,2): error C2374: 'x': redefinition; multiple initialization
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(3): message : see declaration of 'x'
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,7): error C2440: 'initializing': cannot convert from 'int' to 'int *'
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,4): message : Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
1>Done building project "learnCpp.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
however I don't get any errors if I assign the value to x inside the main function.
Like so:
#include <iostream>
int* x = new int;
int main()
{
*x = 5;
}
How come?
In the file scope in C you may place only declarations. You may not execute statements in the file scope. The same is valid for C++ where you may place in a namespace only declarations.
Note: In C declarations are not statements while in C++ declarations are statements. Nevertheless except the declaration statement other statements may not be present in a namespace in C++. It is interesting also to note that in C there is a null statement but there is no an empty declaration. While in C++ there may be an empty declaration.
So this program
#include <iostream>
int* x = new int;
*x = 5;
int main()
{
}
is invalid.
These error messages of the compiler
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2374: 'x': redefinition; multiple initialization
message : see declaration of 'x'
mean that the compiler tries to interpret the assignment statement as a declaration.
But this program
#include <iostream>
int* x = new int;
int main()
{
*x = 5;
}
is correct. In this program the assignment statement is present in the outer block scope of the function main.
What you are trying to do is not possible in global scope.
If you need to do this way try to initialize as below :
// good practice
namespace
{
int* x = new int(5);
}
int main()
{
// You can later modify in function scope
*x = 10;
}
You cannot have statements other than declarations, outside of any scope (for simplicity consider a scope whatever is inside brackets). So, compiler is trying to interpret
*x = 5;
as a declaration, so as a pointer to a given type, but does not find the type pointed to, so generates an error.

Pseudo-code given in class that I'm trying to comprehend with the associated lab assignment in c++

So I've tried to figure out what exactly the professor was writing on the board and how it answers the lab assignment we are to do.
This is the lab assignment:
Create a Hash Table and Hash map that holds all of the WORDS in the (given below) Declaration of Independence.
Handle collisions using the chain method. (Note we will not be modifying this table nor doing deletions!)
Programmatically answer the following questions:
What is the size of your hash table?
What is the longest collision (ie. Chain)
What is the most frequently used word and how did you determine it?
Create a (second) Hash Table that holds all of the LETTERS in the Declaration of Independence.
What is the size of your hash table
What letter has the longest collision?
And this is the pseudo-code with some modifications that I did to fix some errors:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
class Translate
{
string word;
public:
int trans(string word);
w = word.charAT(0); //gives a letter
return #num;
};
class HashTable
{
int size();
int collision();
int length();
char fword();
public:
Translate t;
list<string> hashTable[29];
bool insert(string word)
{
hashTable[t.trans(word)].push_back(word);
return true;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
HashTable h;
open file f("hash.txt");
//h.insert(word)
while (!f.eof())
{
h.insert(f.word());
}
cout << h.size;
cout << h.collision.length;
cout << h.fword;
return 0;
}
The errors that I have are:
Error 15 error C1903: unable to recover from previous error(s); stopping compilation
Error 5 error C2014: preprocessor command must start as first nonwhite space
Error 4 error C2059: syntax error : 'return'
Error 13 error C2065: 'f' : undeclared identifier
Error 10 error C2065: 'file' : undeclared identifier
Error 8 error C2065: 'open' : undeclared identifier
Error 6 error C2143: syntax error : missing ';' before '}'
Error 1 error C2143: syntax error : missing ';' before '='
Error 11 error C2146: syntax error : missing ';' before identifier 'f'
Error 9 error C2146: syntax error : missing ';' before identifier 'file'
Error 14 error C2228: left of '.eof' must have class/struct/union
Error 3 error C2238: unexpected token(s) preceding ';'
Error 7 error C2238: unexpected token(s) preceding ';'
Error 12 error C3861: 'f': identifier not found
Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 19 IntelliSense: '#' not expected here
Error 17 IntelliSense: class "std::basic_string, std::allocator>" has no member "charAT"
Error 21 IntelliSense: expected a ';'
Error 18 IntelliSense: expected a declaration
Error 22 IntelliSense: identifier "f" is undefined
Error 20 IntelliSense: identifier "open" is undefined
Error 16 IntelliSense: this declaration has no storage class or type specifier
I've never used .c_str and I'm still pretty new to C++ so my knowledge is limited. I can tell that there are places that need an identifier but I think there is a better way to create a "open file". My previous knowledge is C#, HTML, and some Python in which C++ is giving me some difficulty in learning and understanding. Any help and/or insight would be greatly appreciated!
Code is too mangled to understand. However, I'm trying my best to help with the little knowledge of mine on C++ and hash.
Proposed Code Modification
Program entry point : instead of int _tmain(int, _TCHAR*), use int main().This should guarantee you the ability to test things out should you migrate to non-windows compiler.
Source : Unicode _tmain vs main
I would like to help with the remainder, however, the code posted is way too unintelligible. Would be kind if the algorithm is posted for reference.
There are a few things you should change:
Assuming trans() is supposed to be a function definition, not a declaration, and the lines following it are supposed to be the body:
Unless you specifically want to copy the passed string, you should use const string& instead of string.
It should have braces.
w is a char.
std::string defines operator[], so it can be indexed like an array.
I'm not sure what #num is (I assume it's from Python, but I'm not familiar with that), so I'm not sure how you intend to calculate the return value.
[I will thus assume that you want to return w, but as an int instead of a char. If this is the case, it would be simpler to just return word[0];.]
There are a few issues with HashTable's members.
Member functions size(), collision(), length(), and fword() are private. This doesn't appear to be intentional.
Member variables t and hashTable are public, when you likely wanted them to be private. Again, this doesn't appear to be intentional.
The functions aren't actually defined anywhere, unless you didn't show their definitions. This will cause a linking error when you call them.
While this doesn't need to be changed, there's no reason for HashTable::insert() to actually return a value, if it's hard-coded to always return true. Also, as mentioned in 1.1 above, the parameter should probably be const string&.
_tmain() and _TCHAR are a Microsoft extensions, which is available on Visual Studio and some (but not all) compilers aiming for compatibility with it (such as C++Builder). If you want your code to be platform-independent, you likely want main(). [Note that this doesn't need to be changed. If you're only compiling with Visual Studio, you can leave it as is. If you want platform independence, you can easily define _tmain and _TCHAR yourself.]
Opening a file:
Neither open nor file are keywords in C++, nor are they types (although FILE is a C type, it doesn't appear to be what you want). You appear to want std::ifstream.
You shouldn't use !f.eof() as a condition in a while loop, because eofbit won't be set until after reading fails.
fstream has no member function word(). However, the extraction operator, operator>>() will read a single word at a time, if given a parameter that can accept one.
HashTable::size(), HashTable::collision(), HashTable::length(), and HashTable::fword() are functions. To call them, you use operator(). If you just use a function's name directly, you don't call it, but instead refer to it (this can be used to create a function pointer or function reference).
int has no member function length(). Therefore, you cannot call h.collision().length(). In C++, if you chain function calls like that, each function in the chain is treated as if it were a member function of the directly preceding type, not the leftmost type; this means that for every function after the first, the return type of the preceding function is used. (In this case, h.collision() returns an int, so .length() attempts to call member function int::length(). int isn't a class type, and thus doesn't have any member functions.)
So, considering these, your code can be modified as follows:
// Assuming your stdafx.h contains "#include <string>" and "#include <tchar.h>".
// If it doesn't, either put them there, or #include them here.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <list>
// #4: Defining _tmain and _TCHAR
#ifndef _tmain
#define _tmain main
typedef char _TCHAR;
#endif
using namespace std;
class Translate
{
string word;
public:
// #1: Fixing trans().
int trans(const string& word)
{
char w = word[0]; // First letter of word.
return w; // Will be promoted to int.
}
};
class HashTable
{
// #2: Making member functions public, and member variables private.
Translate t;
list<string> hashTable[29];
public:
int size();
int collision();
int length();
char fword();
// #3: Making word a const reference. Changing return type to void.
void insert(const string& word)
{
hashTable[t.trans(word)].push_back(word);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
HashTable h;
// #5.1: Opening the file.
ifstream f("hash.txt");
//h.insert(word)
// #5.2 & 5.3: Reading a word.
std::string word;
while (f >> word)
{
h.insert(word);
}
// #6: Calling functions.
cout << h.size();
cout << h.collision(); // #7: Assuming you wanted to output both h.collision() and
cout << h.length(); // h.length(), I put them on separate lines.
// If you actually DID want h.collision().length(), then
// h.collision() should return a type (or reference to a type)
// with member function length(), or be an instance
// (or reference to an instance) of a class with member function
// length() (instead of being a function).
cout << h.fword();
return 0;
}
You still need to provide bodies for HashTable's member functions, apart from insert(), as well as make any other modifications you desire. You might also want to remove member word from Translate, if it doesn't actually need to store a string.

Passing class/object error

I'm working on an assignment but I can't figure out why I'm getting these errors:
Error 1 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 2 error C2143: syntax error : missing ',' before '&'
Its referring to this line of code
ISBN ( const char* str, const ISBNPrefix &list );
ISBNPrefix is another class in a separate header file, and my professor/school tells us not to change the requirements of the assignment. I just don't understand why I'm getting those 2 errors.
Can anyone clarify?
Forward declaration was needed.
class ISBNPrefix;
class ISBN
{
etc, etc.
};
Error 1 means the compiler sees the line of code as a function declaration without a return type. Maybe you meant
ISBN::ISNB(...);
or
void ISBN(...);
Have you included the other file with #include "otherfile.h" ?

Random string from array

I cannot define a string array for unknown reasons on C++. I need to randomly get a string from this array.
Been trying the following:
string bands[] = { "Rammstein", "Slipknot", "Franz Ferdinand", "Gorillaz" };
I'm getting the following as error:
error C2146: syntax error : missing ';' before identifier 'bands'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C3845: 'SpurdoSparde::Form1::bands': only static data members can be initialized inside a ref class or value type
Just a reminder, I'm using a Windows forms applications. Not sure if it makes any difference whatsoever.
It seems you are not including string and/or not using std::string. The following works:
#include <string>
int main()
{
std::string bands[] = { "Rammstein", "Slipknot", "Franz Ferdinand", "Gorillaz" };
}
If you are after a dynamically sized collection of strings, you should prefer std::vector<std::string> over a C-style array. If you need fixed size, have a look at std::array<std::string, N> or tr1 or boost alternatives if you don't have C++11.
You either didn't include #include <string> or need to add the std:: namespace qualifier to your type:
std::string bands[] = { ... };
Prefer this over doing using namespace std;.
Also, you might should prefer to use a std::vector rather than a plain old C-style array:
std::vector<std::string> bands = { ... };