简体   繁体   中英

How to add another Initialize function to base class but not edit base file?

I am having trouble initializing the class, I want to extend it a bit. This is the baseclass:

basefile.cpp

Class Point3d
{
public:
    Point3d ();
    Point3d (double x, double y, double z);
    Point3d&   set (double x, double y, double z);
    double x, y, z;
}
Point3d :: Point3d (): x (0.0), y (0.0), z (0.0)
{
}
inline Point3d &
Point3d :: set (double xx, double yy, double zz)
{
     x = xx;
     y = yy;
     z = zz;
     return * this;
    }
.....

Edit

I want when declaring Point3D pt {1,1}, it means z = 0, so if I didn't edit the original file, how to add a default initialization function z = 0 on base class but from another file, it looks like this:

Point3d::Point3d(double xx, double yy, double zz=0) { x = xx; y = yy; z = zz; }
//or
Point3d :: Point3d (double xx, double yy)
{
     x = xx;
     y = yy;
     z = 0;
     return * this;
}

I thought of using a derived class, but what I wanted was to extend the base class because I wanted to use the base class directly, I searched the partial class as well as many different ways but still failed.

You can only add members to a class in its definition and there can be only one definition of a class.

Extending classes at a later point is done via inheritance as you note in your question.

If you want to have a function set in your class, you need to declare it in the class definition:

class Point3d
{
public:
    Point3d ();
    Point3d (double x, double y, double z);
    Point3d& set (double xx, double yy, double zz = 0);
    double x, y, z;
};

Also note that you don't need the second definition of set , since you are already using a default argument for z .

You also have a few syntax errors in your code. In particular set lacks return values in its function head.

You can't.

You must declare your member function, member method or constructor inside your class header to define it in another place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM