It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am new to c++ and this one has me stumped. I want to pass a struct to a class (I know they are technically the same) so the class can access the data in the struct. I don't mind if it is passed as a reference or a copy as there will be no changes to the struct within the class. Having said that a reference would probably be better for performance. I can get it all to work fine if I pass the members of the struct individually but the real version will have about 30 members so passing them individually isn't the best option.
My main cpp:
#include "stdafx.h"
#include "myClass.h"
#include <iostream>
using namespace std;
struct foo
{
int num;
double dbl;
};
int _tmain(int argc, _TCHAR* argv[])
{
foo bar;
bar.dbl=3.14;
bar.num=42;
baz qux(); //bar needs to be passed here
cout<<qux.getSum()<<endl;
return 0;
}
Class header:
using namespace std;
class baz
{
public:
baz(); //This is where type of bar (foo) is declared
void setSum(int, double);
double getSum();
private:
double sum;
};
Class cpp:
#include "stdafx.h"
#include "myClass.h"
#include <iostream>
using namespace std;
baz::baz() //this is where bar is called
{
setSum(bar.num, bar.dbl);
}
void baz::setSum(int num, double dbl)
{
sum=num*dbl;
}
double baz::getSum()
{
return sum;
}
So the nub of the question is, how do I get bar into baz?
Solved, put the struct definition into a separate header and included that where ever it was needed. Then just a simple change to the declaration in the class header and everything works perfectly. I have included the new code (minus the VS code for the benefit of Abyx who seems to find it so offensive) in case anyone else has the same problem.
Main cpp:
#include "myClass.h"
#include "foo.h"
#include <iostream>
using namespace std;
int main(int argc, _TCHAR* argv[])
{
foo bar;
bar.dbl=3.14;
bar.num=42;
baz qux(bar);
cout<<qux.getSum()<<endl;
return 0;
}
foo.h:
struct foo
{
int num;
double dbl;
};
myClass.h:
class baz
{
public:
baz(const struct foo&);
void setSum(int, double);
double getSum();
private:
double sum;
};
myClass.cpp:
#include "myClass.h"
#include "foo.h"
#include <iostream>
using namespace std;
baz::baz(const foo& blah)
{
setSum(blah.num, blah.dbl);
}
void baz::setSum(int num, double dbl)
{
sum=num*dbl;
}
double baz::getSum()
{
return sum;
}
Make additional constructor. Something like that:
baz::baz(const foo& st){
setSum(st);
}
void baz::setSum(const foo& st)
{
setSum(st.num, st.dbl);
}
then you can:
int _tmain(int argc, _TCHAR* argv[])
{
foo bar;
bar.dbl=3.14;
bar.num=42;
baz qux(bar); //bar needs to be passed here
cout<<qux.getSum()<<endl;
return 0;
}
Your main program:
#include "stdafx.h"
#include "myClass.h"
#include <iostream>
using namespace std;
struct foo
{
int num;
double dbl;
};
int _tmain(int argc, _TCHAR* argv[])
{
foo bar;
bar.dbl=3.14;
bar.num=42;
baz qux(); //bar needs to be passed here
cout<<qux.getSum()<<endl;
return 0;
}
Well, stdafx.h is a header that only makes sense if you turn on (or omit to turn off) use of Microsoft precompiled headers, which makes the Visual C++ preprocessor behave in decidedly non-standard ways. So better remove that. Also, _tmain is a Windows 9x support macro, that expands to either a standard main or a Microsoft-specific wmain. So ditch that also. Finally, there's no need for the return 0 at the end of a standard main, because that's the default return value of main. Also, what's that getSum? Do you write e.g. getsin or getcos? Better call it just sum. Then,
#include "myClass.h"
#include <iostream>
using namespace std;
struct foo
{
int num;
double dbl;
};
int main()
{
foo bar;
bar.dbl=3.14;
bar.num=42;
baz qux( bar ); // See how easy it is to pass `bar`
cout<<qux.sum()<<endl;
}
For the baz class header file, DO NOT EVER have using namespace std in the global namespace in a header file. I.e. remove that also. Then,
#pragma once
#include -- relevant header --
class baz
{
private:
double sum_;
public:
baz( foo const& blah ): sum_( blah.whatever + something ) {}
void setSum( int const n, double const v ) { sum_ = n*v; }
double sum() const { return sum_; }
};
Note: #pragma once is a de facto standard, but it's not ISO standard.
Related
I'm writing my code on linux . But g++ always tells me"Use of undeclared identifier 'random'".I don't know why I have declare it in "Myvector.h"
my code is like :
Myvector.h
class MyVector {
private:
std::vector<double> data;
const int N;
static bool _bDim;
public:
MyVector(); //默认初始化
MyVector(int a); //设置维度初始化
MyVector(std::initializer_list<double> list);
~MyVector();
double &operator[](int);
MyVector &operator=(const MyVector a) {
MyVector b(outN(a));
this->data = a.data;
return *this;
};
friend MyVector random(int a);
}
#endif // MYVECTOR_H_
Myvector.cpp
#include "Myvector.h"
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
bool MyVector::_bDim = true;
MyVector::MyVector() : N(3) {
data = vector<double>(N, 0.0);
_bDim = false;
};
MyVector::MyVector(int a) : N(a) {
data = vector<double>(N, 0.0);
_bDim = false;
};
MyVector::MyVector(std::initializer_list<double> list) : N(list.size()) {
for (auto i = list.begin(); i != list.end(); i++) {
data.push_back(*i);
}
};
MyVector::~MyVector(){
};
double &MyVector::operator[](int i) { return data[i]; }
MyVector random(int a){
MyVector u(a);
srand(time(NULL));
for(int i=0;i<a;i++){
u[i]=rand();
}
return u;
}
main.cpp
#include "Myvector.h"
#include <iostream>
#include<cstdlib>
#include<math.h>
#include <time.h>
using namespace std;
int main(){
MyVector z=random(1);
return 0;}
In fact ,I just know nothing about it. Is there someone going to help me?Thank you.
Below is nothing meaningful. I just need more words to ask this problem.
In the main function of the main.cpp file the following function is called:
MyVector z=random(1);
This appears to be a function which takes a single int argument. Additionally, there is such a function defined in the Myvector.cpp but not declared in Myvector.h (i.e., the main.cpp file does not see any function declaration for the definition).
Update the Myvector.h header to declare the MyVector random(int a) function. Also, the friend declaration is for a random function with 2 parameters, which doesn't look right.
You have to declare the function random somewhere, e.g.
#include "Myvector.h"
#include <iostream>
#include<cstdlib>
#include<math.h>
#include <time.h>
using namespace std;
MyVector random(int);
int main(){
MyVector z=random(1);
return 0;
}
The problem is random in your main function. That one is not declared.
Declaring a friend function means that function has access to the class as if it were a method. It doesn't declare the function at any time, just allows it inside the class.
Your random function is defined is some header file you have included. In your error message you see the return type of random is long int. And you have declared it as MyVector. I am not sure if math.h or time.h have it.
Solution 1: Change the name of your function.
Solution 2: Put your function in a namespace in order to avoid name ambiguity.
I am trying to work with multi-dimensional arrays.
My goal is to have a separate file for my matrix functions, however I am having trouble with setting the value of V.
Error : ‘V’ was not declared in this scope
Since this error statement is very broad, I could not find a satisfactory answer on my searches.
This is what I want to implement.
main.cpp
#include <bits/stdc++.h>
using namespace std;
#include "prims.h"
int main()
{ int V = 5;
int graph[V][V] = { {... },
{... },
{... },
{... },
{... } };
func1(graph);
func2(graph);
return 0;
}
prims.h
#ifndef PRIMS_H
#define PRIMS_H
#include <bits/stdc++.h>
using namespace std;
int func1(int graph[V][V]);
int func2(int graph[V][V]);
#endif
prims.cpp
#include <bits/stdc++.h>
using namespace std;
#include "prims.h"
int func1(int graph[V][V])
{
// function
}
int func2(int graph[V][V])
{
// function
}
Please comment below if more clarification is required.
Thank you.
Since you want to set the value from main, one alternative is to declare V as global variable in main and as extern const int in prims.h, so that it is visible in prmis.cpp as well.
prims.h
extern const int V;
main.cpp
const int V = 5; //declared as global in main
int main()
{
/* */
}
#include <iostream>
#include <windows.h>
#include <string.h>
#include <functional>
#include <stdint.h>
#include <stdio.h>
using namespace std;
template <typename T>
class someclass {
public:
T value;
int sum(int vl1, int vl2) { return vl1 + vl2; };
};
template <typename T>
class someclass2 {
public:
T value;
void print(const std::function<int(int, int)>& func) {
cout << func(3, 4) << '\n';
};
};
int main(int argc, const char **argv)
{
someclass<int> obj1;
someclass2<int> obj2;
obj2.print(obj1.sum);
}
Compiler show error on last line : error C3867: 'someclass::sum': non-standard syntax; use '&' to create a pointer to member
Note that
int sum(int vl1, int vl2) { return vl1 + vl2; };
doesn't use its owner class' member in any way, it safely can be declared static, in that case this code would work.
The problem with this code is that a member function got a different type from standalone function. It's a member of class someclass, so its type is int (someclass::*)(int, int) and to call it you need an instance of that class.
The literal solution in general case is to hide pass of this inside the functor created by lambda expression:
obj2.print( [&](int a, int b)-> int { return obj1.sum(a,b); } );
You can use std::bind to do that
int main(int argc, const char **argv)
{
someclass<int> obj1;
someclass2<int> obj2;
using namespace std::placeholders;
obj2.print(std::bind(&someclass<int>::sum, &obj1, _1, _2));
}
I am trying to have a static method return a shared_ptr.
It is not compiling and is giving template argument 1 is invalid.
I can not figure out why this is.
Also, stack overflow says my post is mostly code and that I should add more detail. I don't know why this is, as being concise never hurt anyone. My problem is clear cut and and can be detailed easily.
Compiler error
src/WavFile.cpp:7:24: error: template argument 1 is invalid
std::shared_ptr<WavFile> WavFile::LoadWavFromFile(std::string filename)
WavFile.cpp
#include "WavFile.h"
#include "LogStream.h"
#include "assert.h"
using namespace WavFile;
std::shared_ptr<WavFile> WavFile::LoadWavFromFile(std::string filename)
{
ifstream infile;
infile.open( filname, ios::binary | ios::in );
}
WavFile.h
#pragma once
#ifndef __WAVFILE_H_
#define __WAVFILE_H_
#include <fstream>
#include <vector>
#include <memory>
namespace WavFile
{
class WavFile;
}
class WavFile::WavFile
{
public:
typedef std::vector<unsigned char> PCMData8_t;
typedef std::vector<unsigned short int> PCMData16_t;
struct WavFileHeader {
unsigned int num_channels;
unsigned int sample_rate;
unsigned int bits_per_sample;
};
static std::shared_ptr<WavFile> LoadWavFromFile(std::string filename);
private:
WavFile(void);
private:
WavFileHeader m_header;
PCMData16_t m_data16;
PCMData8_t m_data8;
};
#endif
Change the namespace name to something else. Now it clashes with the class' name, since you are using namespace WavFile;. Simple example that illustrates the error:
#include <iostream>
#include <memory>
namespace X // changing this to Y makes the code compilable
{
class X{};
}
using namespace X; // now both class X and namespace X are visible
std::shared_ptr<X> v() // the compiler is confused here, which X are you referring to?
{
return {};
}
int main() {}
If you insist to have the namespace named as the class, then get rid of the using namespace X; and qualify the type, std::shared_ptr<WafFile::WavFile>.
How do I execute a member's function by passing the object and the member's function to another function in c++. I do understand the answer to my question is out there; however, I do not know what this is called. So far I created 2 files, exeFunc.h and exeFunc.cpp. Their code consist of:
exeFunc.h
/*
File: exeFunc.h
Header file for exeFunc Library.
*/
#ifndef EXEFUNC_H
#define EXEFUNC_H
#include "mbed.h"
#include "msExtensions.h"
#include "cfExtensions.h"
#include <map>
class exeFunc
{
public:
exeFunc(msExtensions &msExt, cfExtensions &cfExt);
private:
void _splitFuncFromCmd();
void _attachCallback();
msExtensions &_msExt;
cfExtensions &_cfExt;
//FunctionPointer _p;
};
#endif
exeFunc.cpp
/*
File: exeFunc.cpp
Execute functions in other Sensor libraries/classes
Constructor
*/
#include "mbed.h"
#include "ConfigFile.h"
#include "msExtensions.h"
#include "cfExtensions.h"
#include "exeFunc.h"
#include <map>
#include <string>
using namespace std;
exeFunc::exeFunc(msExtensions &msExt, cfExtensions &cfExt) : _msExt(msExt), _cfExt(cfExt)
{
//_cfExt.checkConfigForFirstStart();
//_p.attach(&_cfExt, &cfExtensions::checkConfigForFirstStart);
//_p.call();
}
void exeFunc::_splitFuncFromCmd()
{
}
void exeFunc::_attachCallback()
{
}
I wrote a completed example, may helps
class MyClass
{
public:
MyClass(int b)
:_b(b)
{
}
int Foo(int a)
{
return a * _b;
}
int _b;
};
typedef int (MyClass::*MFP)(int);
int get_result(MyClass* obj, MFP mfp)
{
int r = (obj->*mfp)(5); // 30
return r;
}
int _tmain(int argc, _TCHAR* argv[])
{
MFP mfp = &MyClass::Foo;
MyClass m(6);
get_result(&m, mfp);
return 0;
}
You call it by another function.if you have an independent function.
To be honesty your question is not completely clear.However :
int F(int,int,int);
int g();
//main scope
F(g(),a,b)