I am getting these errors:
`int one::x' is private within this context |
If you declare ‘something’ private inside a class/struct, that ‘thing’ cannot be accessed from outside the class.
Derived classes don’t make any exception.
1 2 3 4 5 6 7 8 9 10 11 12
|
class MyBase {
public:
private:
int base_x = 2;
};
class MyDerived : public MyBase {
public:
private:
int derived_x = base_x; // I can't! “base_x” is a private member of MyBase
};
|
To access those members, you can use the ‘usual’ getter/setter methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class MyBase {
public:
int getBaseX() const
{
return base_x;
}
private:
int base_x = 2;
};
class MyDerived : public MyBase {
public:
private:
int derived_x = getBaseX(); // Ok, “gatBaseX” is public
};
|
- - -
I am getting these errors:
expected `;' before ':' token |
This line of code is wrong:
x = a : (u, v);
1) ‘x’ a private member of ‘one’;
2) ‘a’ cannot be assigned by parenthesis inside
two::setData() — do use assignment operator ‘=’.
Please note you can use member initializer lists only with class constructors
https://en.cppreference.com/w/cpp/language/initializer_list
3) there’s an extra colon ‘:’, probably left by some copy&paste operation.
- - -
Apart from those, there are other issues.
1)
void yClass::two(int u, int v)
The class name is ‘two’. Did you meant
void two::yClass(int u, int v)
?
Otherwise you are defining a ‘two(int, int)’ method of an unknown class ‘yClass’.
2) A comment in class ‘two’ says:
//Postcondition: x = a; y = b; z = c;
If it is correct, it means this exercise is setting a trap for you.
You need to inizialize the
base class (=‘one’) properties ‘x’ and ‘y’ from the arguments passed to the
derived class ‘two’
setData() method.
Hint: remember there also is a
one::setData() method…
- - -
One last thing, but please don’t take offense. It seems you’re getting worse at indenting your code.
Please consider for who reads (i.e. for us), a well indented code is far easier to understand.
Isn’t it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
#include <iostream>
class one
{
public:
void print() const;
//Outputs the values of x and y
protected:
void setData(int u, int v);
//Postcondition: x = u; y = v;
private:
int x;
int y;
};
void one::setData(int u, int v)
{
x = u;
y = v;
}
class two: public one
{
public:
void setData(int a, int b, int c);
//Postcondition: x = a; y = b; z = c;
void print() const;
//Outputs the values of x, y, and z
private:
int z;
};
void two::setData(int a, int b, int c)
{
x = a : (u, v);
y = b;
z = c;
}
void yClass::two(int u, int v)
{
a = u;
b = v;
}
void two::print() const
{
std::cout << a << ' ' << b << ' ' << c << '\n';
}
|