Reference in constructor

Thank you for you all to help me! I have another question about my program.

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
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

class Unit
{
 protected:
    double value;
    string abbreviation;
    double siFactor;
    string siabbreviation;
    Unit(double v, string a, double sif, string sia) : value(v), abbreviation(a), siFactor(sif), siabbreviation(sia) {}
  public:
    double getValue()	{ return value; }
    string getAbbreviation()	{ return abbreviation; }
    double getSIFactor()	{ return siFactor; }
    string getSIAbbreviation()	{ return siabbreviation; }
    double getSIValue()	{ return (value*siFactor); }
    string asString()
    {
      ostringstream oss;
      oss<<value<<abbreviation<<ends;
      string str = oss.str();
      return str;
    }
    string asSIString()
    {
      ostringstream oss;
      oss<<getSIValue()<<getSIAbbreviation()<<ends;
      string str = oss.str();
      return str;
    }
};

class UnitOfLength : public Unit
{
  public:
    UnitOfLength();
    UnitOfLength(double v, string a, double sif, string sia = "m") : Unit(v, a, sif, sia) {}
};

class Meter : public UnitOfLength
{
    public:
        Meter(double m = 0) : UnitOfLength(m, "m", 1) {}
        Meter(const UnitOfLength& l)
            {
                this->value = l.value * l.siFactor;
            }
};

int main()
{
    Meter m(12);
    cout<<m.asString()<<endl;

    Kilometer k(15);
    cout<<k.asString()<<endl;
    cout<<k.asSIString()<<endl;

    Meter m1(l);
    cout<<m1.getValue()<<endl;

    return 0;
}

When I compile the program with the underlined conversion constructor, it says that value and siFactor is protected. But accorting to the inherance type and the data type, it should work.I have no idea about it. And then I change it as:

Meter(const UnitOfLength& l)
{
this->value = l.getSIValue();
}

It says there is an error.

I am confused about it. Would you please give me some hint?

Thank you very much!
something is missing in the main func.
int main()
{
UnitOfLength l(12, "yd", 0.9144);

Meter m(12);
cout<<m.asString()<<endl;

Meter m1(l);
cout<<m1.getValue()<<endl;

return 0;
}
> It says there is an error.
> I am confused about it. Would you please give me some hint?

Non-static protected members of a base class are accessible to member functions in (and friends of) a derived class only through a pointer to, reference to, or object of of a type that is derived from the base class.

See the example in cppreference: http://en.cppreference.com/w/cpp/language/access

In Meter::Meter(const UnitOfLength& l),
l is not a reference to an object of a class that is derived from UnitOfLength.

Last edited on
Topic archived. No new replies allowed.