Reputation: 171
I am learning classes and I have a task just to practice for myself, and I need to modify this class:
class Object {
// modify this
};
template <typename Object>
void test(){
Object z, y(2);
if (z.x() == y.y()){
const Object x;
if (x.y() == Object::z())
return;
}
}
int main(int argc, char** argv) {
test<Object>();
return 0;
}
Nothing can be changed, only that class, so the code compiles without no errors. I am new to classes and it is hard for me to understand what exactly I have to put into that class so it compiles. I thought I need to make two constructors one with no no parameters and another with one parameter, then those x()
and y()
functions, but I am still getting errors. Well I mean I just did this:
class Object {
public:
Object() {
x1 = 2;
y1 = 2;
}
Object(int a) {
x1 = a;
y1 = a;
}
int x() {
return x1;
}
int y() {
return y1;
}
private:
int x1;
int y1;
};
template <typename Object>
void test() {
Object z, y(2);
if (z.x() == y.y()) {
const Object x;
if (x.y() == Object::z())
return;
}
}
int main(int argc, char** argv) {
test<Object>();
return 0;
}
I would be thankful if you would help me out on how this should look like..
Upvotes: 2
Views: 72
Reputation: 4064
Try this. Turned out somewhat messy (?). Still open to constructive criticism:
class Object {
int foo;
public:
// Both the default constructor and the one that takes an int
Object(const int &i = 1) : foo(i) {}
// Member functions
static int z() { return 1; }
int x() { return 1; }
int y() const { return 1; }
};
As for the second one, try this:
class Object {
int foo;
public:
struct X { // Nested class
int y() { return 2; } // for y.x.y()
};
X x; // for the same
// Both the default constructor and the one that takes an int
Object(const int &i = 1) : foo(i) {}
bool operator<(const Object &o) { return 1; } // for std::sort
int operator()() { return 0; } // for x[0]()
Object operator++(int) { return *this; } // for x[1]++
int y() { return 2; } // for x[1]++y.()
};
Note the use of the nested class. As with the first task, since it is not prohibited, it is permitted. Maybe there's another way to deal with the y.x.y()
but didn't come up with anything more elegant (will be glad to accept any input and suggestions!).
Upvotes: 1