C++ redefinition
I am trying to implement a function class, but got a error of redefinition. I 开发者_开发知识库know it is stupid, but can anyone please help?
=== header file ===
#ifndef _NS4_h
#define _NS4_h
#include <vector>
#include <list>
namespace NS4{
class complex{
double r, i;
public:
complex(double a=0, double b=0) : r(a), i(b) {};
complex operator+(complex c);
complex &operator+=(complex c);
complex &operator=(complex c);
};
// function class
class Add{
complex val;
public:
Add(complex c){ val = c; }
Add(double r, double i) { val = complex(r, i); }
void operator()(complex& c) const { c += val; }
};
void h(std::vector<complex> &aa, std::list<complex> ll, complex z);
}
#endif
=== Part of the cpp file ===
using namespace NS4;
void test9()
{
vector<complex> aa;
aa.push_back(complex(0,1));
aa.push_back(complex(0,2));
aa.push_back(complex(0,3));
list<complex> ll;
ll.push_back(complex(1,1));
ll.push_back(complex(1,2));
ll.push_back(complex(1,3));
complex zz(1,1);
// the following line is not working
// error C2371: 'zz' : redefinition; different basic types
Add(zz); // Add(complex(1,1)) is working.
h(aa,ll, zz);
}
You have an Add class, so you need to create an instance of it, in order to call the constructor.
So in the below case, a
is an instance of our Add
class.
Add a(zz);
You can optionally put parenthesis around the variable name in a declaration.
int (i);
is the same as
int i;
So in your case you are declaring a variable named zz
of type Add
, and a variable named zz
already exists. You probably meant to pass zz
as an argument to Add
constructor, but then you should give some name to the variable:
Add adder(zz);
However, I don't see where that instance is used at all.
But if you just want to invoke the constructor of Add
without declaring a variable, you can put parenthesis around the whole expression:
(Add(zz)); //just calls Add::Add(Complex);
Welcome to C++ ;)
What is Add(zz)
supposed to mean? What do you think it means?
Add(zz)
is actually a declaration of object zz
of type Add
, i.e.
Add(zz);
is equivalent to
Add zz;
You have already defined zz
before, which is why you get the redefinition error. No surprise here.
There's no way to help you further without knowing what you were trying to do by that Add(zz)
line.
精彩评论