简体   繁体   中英

Need help inserting a string into a function

I am looking to make repeated programming a little bit easier going forward. The program tells a motor to spin based on the manufacturers program guidelines. The current code will state:

motorname.spin(originallib::directionType::fwd, speed, originallib::velocityUnits::pct);

I want to be able to say:

int main()
{
run(LeftFront,80);
run(RightFront,80);
}

void run(string motorname, double speed )
{
motorname.spin(originallib::directionType::fwd, speed, originallib::velocityUnits::pct);
}

LeftFront and RightFront have been declared in a previous header file as

originallib::motor LeftFront=originallib::motor(originallib::PORT2,
                                                originallib::gearSetting::ratio18_1,
                                                true);

The issue I am running into is:

"error: no member named 'spin' in 'std::basic_string' "

Because the motorname.spin ..... is part of the originallib

How can I go about achieving this?

void run(string motorname, double speed )

Tells the compiler that motorname is a std::string . std::string has no spin method. Based on

run(LeftFront,80);

where LeftFront is a originallib::motor , and assuming originallib::motor does indeed have a spin method, you really the function to look something like

void run(originallib::motor & motor, 
         double speed)
{
    motor.spin(originallib::directionType::fwd, 
               speed, 
               originallib::velocityUnits::pct);
}

so that a motor that can spin is provided instead of a string that can at best std::rotate

An alternative using names would be to have a map of string -> motor key-value pairs that you can look up a motor name in the map and receive the mapped motor , on which you could invoke spin . This does not seem to be a desirable case here.

Sidenote:

You do not want to

originallib::motor LeftFront=originallib::motor(originallib::PORT2,
                                                originallib::gearSetting::ratio18_1,
                                                true);

in a header. This plays havoc on the One Definition Rule if multiple Translation Units include the header as each including translation unit will have its own, equally valid, LeftFront . Include guards will not prevent this because an include guard can only prevent a header from being included multiple times in one translation unit.

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