Using functions within functions - c++

Below is a piece of code I was trying to run where I have function I want to run (dN) within my main function which returns a value of type complex<double>.
#include <iostream>
#include <complex>
#include <cmath>
using namespace std;
const complex<double> Im1(0.0,1.0); //imaginary number definition
class Functions{
public:
complex<double> dN(complex<double> **N, int k, int i, complex<double> kN, double T1){
complex<double> OUT = Im1*(N[k][i]+kN)/(T1);
return OUT;
};
};
int main(int argc, const char * argv[]) {
//...more code here
complex<int> **NM = new complex<int>*[1000]; //1000x500 array
//run loop to initialize
for (int i = 0; i < 1000; ++i)
{
NM[i] = new complex<int>[500];
}
complex<double> dN_OUT = Functions::dN(**NM,1,20,0.,20.);
return 0;
};
Although this code does not run and returns the error: Call to non-static member function without an object argument
Based on my understanding, C++ does not allow nested functions and my code above would not work because I call a separate function in my main function. Although (based on the link) it does appear one can implement "local classes" by defining a function within a struct which would have to be inside the main function. Although when I try doing that:
int main(int argc, const char * argv[]) {
complex<int> **NM = new complex<int>*[1000]; //1000x500 array
//run loop to initialize
for (int i = 0; i < 1000; ++i)
{
NM[i] = new complex<int>[500];
}
struct Functions{
complex<double> dN(complex<double> **N, int k, int i, complex<double> kN, double T1){
complex<double> OUT = Im1*(N[k][i]+kN)/(T1);
return OUT;
};
};
complex<double> dN_OUT = Functions::dN(**NM,1,20,0.,20.);
return 0;
};
the error persists. Ultimately, I am simply wanting to use the function dN that returns output of type complex<double> within my main function, but am unsure of the best/operational way to implement this.

I believe you misunderstand what a nested function is.
A nested function would look like this:
int main()
{
void nested() {} // not allowed in C++
}
The solution to your problem is in the error message provided by your compiler:
Call to non-static member function without an object argument
Take a look at the following:
// Example 1
struct Functions {
void func() {}
};
int main()
{
// to call Functions::func() you would need to have an object
// of type Functions because Functions::func() is not a static function
Functions f;
f.func();
}
// Example 2
// by making func() static you can call it without an object:
struct Functions {
static void func() {}
};
int main()
{
Functions::func(); // OK
}

Ultimately, I am simply wanting to use the function dN that returns output of type complex within my main function, but am unsure of the best/operational way to implement this.
Use a free function, like main is, unless dN has a specific reason to be part of a class:
complex<double> dN(complex<double> **N, int k, int i, complex<double> kN, double T1)
{
...
}
int main(int argc, const char * argv[]) {
...
//like this
complex<double> dN_OUT = dN(NM,1,20,0.,20.);
//not like this
//complex<double> dN_OUT = dN(**NM,1,20,0.,20.);
}

Option 1:
You can do this with class like below
#include <iostream>
#include <complex>
#include <cmath>
using namespace std;
const complex<double> Im1 (0.0, 1.0); //imaginary number definition
class Functions {
public:
complex<double> dN (complex<double> **N, int k, int i, complex<double> kN, double T1)
{
complex<double> OUT = Im1*(N[k][i] + kN) / (T1);
return OUT;
};
};
int main (int argc, const char * argv[]) {
//...more code here
complex<double> **NM = new complex<double>*[1000]; //1000x500 array
//run loop to initialize
for (int i = 0; i < 1000; ++i)
{
NM[i] = new complex<double>[500];
}
Functions fun; //create class instance
//call the function NOTE the changes here i.e not correct passing **NM
complex<double> dN_OUT = fun.dN (NM, 1, 20, 0., 20.);
return 0;
};
Option 2 (mentioned by others direct calling with changes instead of **NM you should use NM.
complex<double> dN(complex<double> **N, int k, int i, complex<double> kN, double T1){
...
}
int main(int argc, const char * argv[]) {
...
complex<double> dN_OUT = dN(NM,1,20,0.,20.);
}

Related

Header file C++

when i'm trying to compile program but it says that i have an error in row when i'm to create a function pow(int base ,int exp),it says that 'pow': illegal qualified name in member declaration,here's my code:
Math.h:
#pragma once
static class Math {
public:
static int Math::pow(int base,int exp);
};
Math.cpp:
#include "Math.h"
int Math::pow(int base, int exp)
{
int result = 1;
for (int i = 0; i < exp; i++)
{
result = result * base;
}
return result;
}
Line:
static int Math::pow(int base,int exp);
Does not need the Math:: prefix since it is in the Math class declaration.
The class definition is probably intended to look like this:
class Math {
public:
static int pow(int base,int exp);
};
static before the class has no meaning and is not allowed syntax.
The member function declaration doesn't need (and isn't allowed to) have a qualified name. It belongs to the class already because it is declared in the class scope. There is no need to qualify it any further.
From what you are doing it does seem however that you really want to have a namespace, not a class:
// Header file
namespace Math {
int pow(int base,int exp);
}
// Source file
namespace Math {
int pow(int base, int exp)
{
int result = 1;
for (int i = 0; i < exp; i++)
{
result = result * base;
}
return result;
}
}

Are C++ function declarations optional?

I just noticed something when creating functions. In the code:
#include <iostream>
using namespace std;
int add(int a, int b = 20)
{
int r;
r = a + b;
return (r);
}
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
it will work because the function being called is on top of the caller, but if I put the function add() below the calling function in main() it won't work.
#include <iostream>
using namespace std;
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
int add(int a, int b = 20)
{
int r;
r = a + b;
return (r);
}
and the compiler will tell me that the identifier add() cannot be found.
so why do we declare functions anyway? like this:
#include <iostream>
using namespace std;
int add(int a, int b = 20);
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
int add(int a, int b)
{
int r;
r = a + b;
return (r);
}
A definition is implicitly a declaration. And a declaration must come ahead of the use.
All functions need to be declared before they are used.
You can do that by either (1) writing a declaration, or (2) writing a definition.
Relying solely on (2) can be tempting but then you are bound to order your program in a particular way, and is occasionally impossible. For example, the following will not compile unless the comment is removed.
//void bar(int);
void foo(int n)
{
if (!n){
bar(n);
}
}
void bar(int n)
if (n){
foo(n);
}
}
int main()
{
foo(1);
}
No.
If the function definition appears before the function call, then prototype is not mandatory. Otherwise function prototype is necessary to let compiler know how to respond to a function when it is called.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
if the function definition appears after the function call then prototype is mandatory. because it tells the compiler to how to respond the function when it is called.
check the following example.
/* C++ Function Prototype and C++ Function Definition */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int add(int, int); // function prototype
void main()
{
clrscr();
int a, b;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\nSummation = "<<add(a, b);
getch();
}
int add(int x, int y) // function definition
{
int res;
res = x + y;
return res;
}
and if the function definition is made before the function call then it is not mandatory to declare function prototype.
consider example.
/* C++ Function Prototype and C++ Function Definition */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int add(int x, int y) // function definition
{
int res;
res = x + y;
return res;
}
void main()
{
clrscr();
int a, b;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\nSummation = "<<add(a, b);
getch();
}

Assign vector<bool>

I'm trying to assign a vector bool as follows:
#include <iostream>
#include <vector>
using namespace std;
struct item {
int value;
vector<bool> pb;
vector<bool> *path = &pb;
};
int main(int argc, char* argv[]) {
vector<item> dp(10);
for (int n = 0; n < 10; n++)
dp[n].pb = vector<bool>(10);
}
It compiles ok but get the following runtime error:
An invalid parameter was passed to a function that considers invalid parameters fatal.
The value of dp and n are
How can I assign a vector bool to an existing variable?

Cannot correctly print integers that are returned from a function in C++

I am trying to program something for a class that involves creating an object using a Token class and printing it out. Here is my main method:
int main(int argc, char** argv) {
Token tok(10, "test", 1, 2);
printf("%d\n", tok.type());
}
This is my Token.cc file with relevant methods:
Token::Token(int t, string str, int l, int c) {
int tokType = t;
string lexStr = str;
int lineNum = l;
int charPos = c;
}
int Token::type() {
return tokType;
}
And this is my Token.h file:
#ifndef TOKEN_H
#define TOKEN_H
using namespace std;
#include <string>
class Token{
private:
public:
Token(int t, string str, int l, int c);
~Token();
int type();
int tokType;
string lexStr;
int lineNum;
int charPos;
};
#endif
Program compiles fine, however when I run it prints a seemingly random number such as 1475212264 or -258154088 or some other random number of that length.
Any ideas what could be going wrong? This is driving me crazy.
Thanks
I believe that in your constructor, because you are redefining all of your variables, you are limiting their scope to the constructor. What this amounts too is that the member variables of the Token class end up not being set to the values you passed to the constructor. So you end up with uninitialized data as a result of type().
Just try removing the datatypes in the constructor like so:
Token::Token(int t, string str, int l, int c) {
tokType = t;
lexStr = str;
lineNum = l;
charPos = c;
}
And see if that helps.

serialize std::function with variable parameters

my question is somewhat related to this question: Serialize C++ functor, but still different. It is a followup to this question: Passing a closure as a parameter to a constructor c++
Basically I have code that looks like this:
#include <iostream>
#include <string>
#include <functional>
using namespace std;
class Event
{
public:
std::function<double()> func;
template <typename T>
Event(T func): func(func) {}
virtual double execute()
{
double endtime = func();
return endtime;
}
};
double foo(int v1, int v2)
{
return(v1/(v2 * 1.0));
}
int main(int argc, char* argv[])
{
int a = 3;
int b = 4;
Event* e = new Event([=]() -> double{return foo(a, b);});
cout << e->execute() << endl;
int y;
std::cin >> y;
}
Is there a way to serialize func? I'd like to be able to save and load the function pointer AND the values to the parameters that the function it points to needs.
the output of the above is:
0.75
I'm using MSVS 2012, but would consider changing to MSVS 2013 if an answer requires features only available in the latter.